<?php

namespace Admin\Frontend\Controllers;

use Admin\Models\group\XhsysGroup;
use Admin\Models\group\XhsysGroupuser;
use Admin\Models\ims\XHImsReturnTab;
use Admin\Models\overt\XhovertAreainfo;
use Admin\Models\res\XhresArticle;
use Admin\Models\school\XhProjectHistory;
use Admin\Models\school\XhschoolApply;
use Admin\Models\school\XhschoolShare;
use Admin\Models\school\XHSchoolVisit;
use Admin\Models\stats\XhstatsExamine;
use Admin\Models\user\XhsysUserComment;
use Admin\Models\sys\XhsysUserTch;
use Admin\Models\user\XhsysUserHistory;
use Endroid\QrCode\QrCode;
use Helpers\Area;
use Helpers\Hrm;
use Helpers\Tool;
use Helpers\Main;
use Helpers\Cache;
use Helpers\Device;
use Helpers\Assets;
use Helpers\Template;
use Helpers\EnumList;
use Helpers\HttpClient;
use Helpers\User;
use Helpers\XhException;
use Modules\Charge;
use Modules\Power;
use Modules\School;
use Phalcon\Mvc\View;
use Phalcon\Db\Adapter\Pdo\Mysql;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\user\XhsysUser;
use Admin\Models\user\XhsysUserPayVoucher;
use Admin\Models\user\XhsysUserPayVoucherLog;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\school\XhschoolAppgroup;
use Admin\Models\school\XhschoolAppgroupapp;
use Admin\Models\school\XhschoolUserappgroup;
use Admin\Models\school\XhschoolAppstore;
use Admin\Models\school\XhschoolFocus;
use Admin\Models\device\XhsysUsertablet;
use Admin\Models\device\XhsysAccountdevicelocked;
use Admin\Models\user\XhsysUserstud;
use Admin\Models\school\XhschoolExamine;
use Admin\Models\cost\XhcostStudcharge;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\track\XhtrackTch;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use Services\Auth;
use Services\ResBase;
use Services\UserService;
use Services\ResAreaGroup;

class SchoolController extends ControllerBase
{

    private $userEnum = [
        'iUserSex' => [1 => '男', 2 => '女'],
        'bCompany' => [0 => '否', 1 => '是'],
        'bEbook' => [0 => '', 1 => '<i class="fa fa-check"></i>'],
        'iPoorLevel' => [0 => '', 1 => '一级', 2 => '二级'],
        'iDevSource' => [0 => '', 1 => '购买', 2 => '租用', 3 => '借用', 4 => '自购'],
        'iTchChild' => [1 => '', 2 => '收费教师子女', 3 => '免费教师子女'],
        'iBehind' => [0 => '否', 1 => '是'],
        'iHistoryType' => [0 => '', 1 => '转校', 2 => '毕业', 3 => '退用'],
        'iType' => [1 => '正式', 2 => '测试', 3 => '体验', 4 => '临时', 5 => '培训']
    ];
    private $schEnum = [
        'iStatus' => [0 => '未上线', 1 => '上线', 2 => '运营', 3 => '停运', 4 => '测试'],
        'bWelfare' => [0 => '否', 1 => '是'],
        'iStage' => [1 => '小学', 2 => '初中', 3 => '高中'],
        'iType' => [0 => '普通学校', 1 => '培训机构'],
        'iApprovalStatus' => [0 => '未审核', 1 => "<i class='glyphicon glyphicon-ok'>已审核</i>"],
        'iExamineMode' => [1 => '全校', 2 => '年级']
    ];
    private static $tchEnum = [
        'bImportant' => [0 => '全部', 2 => '重要教师', 1 => '非重要教师'],
        'bExcellent' => [0 => '全部', 2 => '优秀教师', 1 => '非优秀教师'],
    ];

    private static $payVoucherState = [
        1 => '待审核',
        2 => '通过',
        3 => '未通过',
    ];

    private function runEnum()
    {
        $this->schEnum['iRunLevel'] = XhsysEnum::getEnumByNodeName('运营等级');
        $this->schEnum['iMainRunUserId'] = Hrm::getDepStaffByTag('XHYYB');
        $this->schEnum['sRunUserId'] = $this->schEnum['iMainRunUserId'];
//        $this->schEnum['focusLevel'] = XhsysEnum::getEnumByNodeName('关注程度');
        $areaObj = new Area();
        $provArr = $areaObj->getAllProvinces(true);
        foreach ($provArr as $item) {
            $pro[$item] = $item;
        }
        $this->schEnum['sProvinceName'] = ['' => '-选择省-'] + $pro;
    }

    /**
     * 获取关注程度枚举
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171118
     */
    public function getFocusLevelAction()
    {
        return $this->sendJsonResponse(XhsysEnum::getEnumByNodeName('关注程度'));
    }

    /**
     * 学校列表页面
     *
     * create by ck 20160316
     * modify by ck 20160620    优化
     * modify by ck 20160810
     * modify by ck 20160926    js压缩，搜索框
     * modify by sqb 20190109   调整显示字段
     */
    public function indexAction()
    {
        $this->view->pick('school/schoolList');
        Main::showNavPosition();
        Assets::select2();
        Assets::easyUI('js/school/schoolList.js');
        Assets::xhChart();
        if (!Power::exist('School_List')) {
            return $this->sendViewError('无查看权限');
        }
        $listButtonArr = $formButtonArr = $listSearchArr = [];
        if (Power::exist('School_List_Add')) {
            $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_add', 'text' => '增加', 'icon' => 'fa-plus'];
        }
//        if (Power::exist('School_List_Edit')) {
//            $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_edit', 'text' => '修改', 'icon' => 'fa-pencil'];
//        }
        if (Power::exist('School_List_Del')) {
            $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash'];
        }
        if (Power::exist('School_List_ContactQBank')) {
            $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_contact', 'text' => '关联题库', 'icon' => 'fa-pencil'];
        }
        if (Power::exist('School_List_UpdateClass')) {
            $listButtonArr[] = [
                'plain' => 'true', 'id' => 'bt_list_update_class', 'text' => '升级班级', 'icon' => 'fa-arrow-up'
            ];
            $listButtonArr[] = [
                'plain' => 'true', 'id' => 'bt_list_syn_group', 'text' => '同步应用组', 'icon' => 'fa-exchange'
            ];
        }
        //处理周报权限
        $power['weekly'] = ['add' => false, 'view' => false];
        if (Power::exist('School_List_Weekly')) {
            $listButtonArr[] = [
                'plain' => 'true',
                'id' => 'bt_list_weekly',
                'text' => '周报',
                'class' => 'easyui-menubutton',
                'icon' => 'fa-newspaper-o'
            ];
            $power['weekly']['view'] = true;
            if (User::isAdmin()) {
                $power['weekly']['add'] = true;
            } else {
                $allowWeek = explode(',', Main::getConfigByName('school')['allowAddWeekly'] ?: '');
                $power['weekly']['add'] = in_array(date('w'), $allowWeek);
            }
        }

        $listSearchArr[] = [
            'type' => 'select',
            'id' => 'list_search_status',
            'data' => array_merge(['' => '--状态--'], EnumList::getFieldEnumList('iStatus'))];
        //添加省市区+运营区域
        $area = XhovertAreainfo::find([
            'conditions' => ' areaLevel = :level:',
            'bind' => ['level' => 1]
        ])->toArray();
        $area = array_column($area, null, 'areaCode');
        $enums['province'] = array_column(array_values($area), 'areaName', 'areaCode');
        $enums['province'][''] = '--请选择省--';
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_province', 'data' => $enums['province'], 'default' => '');
        $enums['city'][''] = '--请选择市--';
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_city', 'data' => $enums['city'], 'default' => '');
        $listSearchArr[] = ['label' => ' ', 'type' => 'select', 'id' => 'list_depart', 'style' => 'width:120px;'];

        $listSearchArr[] = ['type' => 'text', 'id' => 'list_search_vague', 'label' => ' 搜索： '];
        $listButtonArr[] = ['id' => 'bt_list_group_status', 'text' => '题舟分组', 'icon' => 'fa-refresh'];
//        $listButtonArr[] = ['id' => 'bt_list_knowledge', 'text' => '学情查看', 'icon' => 'fa-graduation-cap'];
        if (Power::exist('School_List_RefreshLogin')) {
            $listButtonArr[] = ['id' => 'bt_list_refresh_login', 'text' => '刷新登陆', 'plain' => 'true', 'icon' => 'fa-refresh'];
        }
        $this->runEnum();

        $power['runCase'] = Power::exist('School_RunCase');
        $power['activity'] = Power::exist('School_Activity');
        $power['schoolShare'] = Power::exist('School_Share');
        $power['tchBook'] = true;
        $power['bookVer'] = Power::exist('School_BookVer');
        $power['schoolVisit'] = Power::exist('School_Visit');
        $power['schoolStat'] = Power::exist('School_Stat');

        $powerTags = [
            'School_List_Stud',//学生管理
            'School_List_Tch',//教师管理
            'School_List_Group',//应用组管理
            'School_List_Manage',//学校管理
            'School_List_App',//应用管理
            'School_List_QBank',//题库管理
            'School_List_OtherUser',//其他用户
            'School_List_BrushGroup',//刷题王分组
            'School_List_Books',//校本库
        ];
        foreach ($powerTags as $powerTag) {
            if (Power::exist($powerTag)) {
                $power[$powerTag] = Power::exist($powerTag);
            }
        }

        $field = ['iStatus', 'iSchoolId', 'sSchoolName', 'sCode', 'iStage', 'iRunLevel', 'iType', 'iApprovalStatus', 'bWelfare', 'iExamineMode', 'brushGroupStatus', 'iSchoolIdModify'];
        if ($power['schoolStat']) {
            $field[] = 'class';
            $field[] = 'teacher';
            $field[] = 'student';
        }

        return $this->view->setVars([
            'List' => Template::createList('list', 'School_Info', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
                'field' => $field
            ]),
            'Form' => Template::createForm('XHSchool_Info', $this->schEnum),
            'FormButton' => Template::createButtonToolBar(Main::createFormButton('School_List')),
            'power' => $power
        ]);
    }

    /**
     * 根据页码及每页行数获取数据并以json格式返回
     *
     * create by ck 20160304
     * modify by ck 20160620    优化
     * modify by ck 20160810
     * modify by ck 20160926    添加模糊查询
     * modify by ck 20161226
     * modify by ck 20171108    添加权限判断
     * modify by dale 20171225  左连接考核分数，添加传入参数month
     * modify by ck 20180508    添加考核方式
     * modify by sqb 20190108   添加学生、班级、教师数量
     * modify bt sqb 20190128   添加区域筛选
     */
    public function getDgDataAction()
    {
        $support = $this->request->getPost('support', 'int');
        $status = $this->request->getPost('status', 'int');
        $weekly = $this->request->getPost('weekly');
        $province = $this->request->get('province', 'int');
        $city = $this->request->get('city', 'int');
        $depart = $this->request->get('depart', 'int');

        try {
            $parameters = array(
                'columns' => 'iSchoolId,sSchoolName,iStatus,bWelfare,sAbbr,iStage,iRunLevel,iType,sCode,iApprovalStatus,iExamineMode',
                'conditions' => 'bDelete = 0',
            );
            if ($support) {
                $parameters['conditions'] .= ' AND (iStatus = 1 OR iStatus = 2)';
            }
            if ($status != '') {
                $parameters['conditions'] .= ' AND iStatus = ' . $status;
            }

            if ($province) {
                $parameters['conditions'] .= ' AND sProvinceCode = ' . $province;
            }
            if ($city) {
                $parameters['conditions'] .= ' AND sCityCode = ' . $city;
            }
            $flag = 0;
            if ($depart) {
                $staff = $this->db->fetchOne("select iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$depart},%'");
                $authId = $staff['iUserId'];
                if (!$authId) {
                    return $this->sendJsonResponse([]);
                }
                $schoolArr = User::getSchool(true, $authId, true);
                if (!empty($schoolArr)) {
                    $schoolIds = implode(',', array_keys($schoolArr));
                    $schoolList = XhschoolInfo::find([
                        'conditions' => "bDelete = 0 AND (iStatus = 1 OR iStatus = 2) AND iSchoolId in ({$schoolIds})",
                        'columns' => 'iSchoolId,sSchoolName',
                    ])->toArray();
                    $schoolIds = implode(',', array_keys(array_column($schoolList, null, 'iSchoolId')));
                    $parameters['conditions'] .= " AND iSchoolId in ({$schoolIds})";
                    $flag = 1;
                }
            }

            $schoolIds = School::getPower();
            if (!$schoolIds) {
                return $this->sendDataGridError('无学校权限');
            } elseif ($schoolIds !== true && $flag == 0) {
                $parameters['conditions'] .= ' AND iSchoolId IN (' . implode(',', $schoolIds) . ') ';
            }

            Main::runSearchVagueConditions($parameters['conditions'], ['iSchoolId', 'sSchoolName'], [], [], true);
            $this->runEnum();
            $data = Main::runModelPage('\\Admin\\Models\\school\\XhschoolInfo', $parameters, $this->schEnum);

            if ($weekly) {
                $ids = implode(',', array_column($data['rows'], 'iSchoolId'));
                $sql = "select iSchoolId from XHSchool_Weekly WHERE bDelete = 0 AND iSchoolId in ({$ids})  GROUP BY iSchoolId";
                $week = $this->db->fetchAll($sql);
                $week = array_column($week, null, 'iSchoolId');
                foreach ($data['rows'] as $index => $row) {
                    if (isset($week[$row['iSchoolId']])) {
                        $data['rows'][$index]['sSchoolName'] .= '<i class="fa fa-newspaper-o fa-lg fa-fw" style="color:#2baab1;"></i>';
                    }
                }
            }

            foreach ($data['rows'] as &$datum) {
                switch ($datum['iStatus']) {
                    case '未上线':
                        $datum['iSchoolIdModify'] = "<p class='bg-warning' status='0' style='text-align: center; margin: auto;'>{$datum['iSchoolId']}</p><p class='display_none' style='text-align: center; margin: auto;'>未上线</p>";
                        break;
                    case '上线':
                        $datum['iSchoolIdModify'] = "<p class='bg-info' status='1' style='text-align: center; margin: auto;'>{$datum['iSchoolId']}</p><p class='display_none' style='text-align: center; margin: auto;'>上线</p>";
                        break;
                    case '运营':
                        $datum['iSchoolIdModify'] = "<p class='bg-light-green' status='2' style='text-align: center; margin: auto; color: #ffffff'>{$datum['iSchoolId']}</p><p class='display_none' style='text-align: center; margin: auto;'>运营</p>";
                        break;
                    case '停运':
                        $datum['iSchoolIdModify'] = "<p class='bg-danger' status='3' style='text-align: center; margin: auto;'>{$datum['iSchoolId']}</p><p class='display_none' style='text-align: center;margin: auto;'>停运</p>";
                        break;
                    case '测试':
                        $datum['iSchoolIdModify'] = "<p class='bg-grey' status='4' style='text-align: center; margin: auto;'>{$datum['iSchoolId']}</p><p class='display_none' style='text-align: center;margin: auto;'>测试</p>";
                        break;
                    default:
                        break;
                }
            }

            if (Power::exist('School_Stat')) {
                foreach ($data['rows'] as &$datum) {
                    $schoolId = $datum['iSchoolId'];
                    $studentNumber = XhsysUser::getUserNumbersBySchoolId($schoolId, 1);
                    $teacherNumber = XhsysUser::getUserNumbersBySchoolId($schoolId, 4);
                    $class = XhsysUser::getClassInfoBySchoolId($schoolId);
                    $datum['student'] = $studentNumber;
                    $datum['teacher'] = $teacherNumber;
                    $datum['class'] = $class['classNum'];
                }
            }

            return $this->response->setJsonContent($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 根据学校id获取信息
     *
     * @param $schoolId
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170818
     * modify by ck 20171118    添加学段关注程度
     */
    public function getSchoolInfoAction($schoolId)
    {
        $schoolInfo = XhschoolInfo::findFirst($schoolId)->toArray();
        $focusInfo = XhschoolFocus::find([
            'columns' => 'iGradeCode,iFocusLevel',
            'conditions' => 'bDelete = 0 AND iSchoolId = :schoolId:',
            'bind' => ['schoolId' => $schoolId]
        ])->toArray();
        $schoolInfo['focusLevel'] = array_column($focusInfo, 'iFocusLevel', 'iGradeCode');
        $schoolInfo['sRunUserId'] = trim($schoolInfo['sRunUserId'], ',');
        return $this->response->setJsonContent($schoolInfo);
    }

    /**
     * 插入新数据
     *
     * create by ck 20160304
     * modify by ck 20160621    优化
     * modify by ck 20171115    更改结构
     * modify by ck 20171118    学段关注程度添加
     */
    public function modifyDataAction()
    {
        $postData = $this->request->getPost();
        if (!isset($postData['sProvinceName']) || !isset($postData['sCityName']) || !isset($postData['sCountyName']) ||
            empty($postData['sProvinceName']) || empty($postData['sCityName']) || empty($postData['sCountyName'])) {
            return $this->sendErrorResponse(400, '请填写所属地区');
        }
        $obj = XhschoolInfo::createRecord($this->request->getPost());
        $new = $obj->iSchoolId ? false : true;
        if (!Power::exist('School_List_' . ($new ? 'Add' : 'Edit'))) {
            return $this->sendErrorResponse(400, '无操作权限');
        }
        $this->db->begin();
        try {
            if (!$obj->save()) {
                throw new \Exception('保存失败');
            }
            //处理年级关注程度
            $focusLevel = $this->request->getPost('focusLevel', 'int');
            if ($focusLevel) {
                $focusObj = XhschoolFocus::find([
                    'conditions' => 'bDelete = 0 AND iSchoolId = :schoolId:',
                    'bind' => ['schoolId' => $obj->iSchoolId]
                ]);
                if (!$focusObj->toArray() || $focusObj[0]->iStage != $obj->iStage) {
                    if ($focusObj && !$focusObj->delete()) {
                        throw new \Exception('处理原关注程度失败');
                    }
                    foreach ($focusLevel as $code => $level) {
                        $focus = new XhschoolFocus();
                        $focus->iSchoolId = $obj->iSchoolId;
                        $focus->iStage = $obj->iStage;
                        $focus->iGradeCode = $code;
                        $focus->iFocusLevel = $level;
                        if (!$focus->save()) {
                            throw new \Exception('关注程度新建失败');
                        }
                    }
                } else {
                    foreach ($focusObj as $focus) {
                        if (isset($focusLevel[$focus->iGradeCode])) {
                            $focus->iFocusLevel = $focusLevel[$focus->iGradeCode];
                            if (!$focus->save()) {
                                throw new \Exception('关注程度保存失败');
                            }
                        }
                    }
                }
            }
            School::refresh();
            $this->db->commit();
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getTraceAsString());
        }
        return $this->sendSuccessResponse('保存成功');
    }

    /**
     * 根据省名字获取市数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Exception
     * @throws \Lybc\PhpGB2260\InvalidCodeException
     *
     * create by qgz 20180808
     */
    public function getCityDataByProvAction()
    {
        $provId = $this->request->getPost('provId');
        if (empty($provId)) {
            return $this->sendJsonResponse(['' => '-请选择市-']);
        }
        $id = '';
        try {
            $areaObj = new Area();
            $provArr = $areaObj->getAllProvinces(true);
            foreach ($provArr as $key => $item) {
                if ($item == $provId) {
                    $id = $key;
                    break;
                }
            }
            $return = [];
            $areaObj = new Area((int)$id);
            $allCity = $areaObj->getCity();
            foreach ($allCity as $value) {
                $return[$value] = $value;
            }
            $return = ['' => '-请选择市-'] + $return;
            return $this->sendJsonResponse($return);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(400, '学校还没有设置所属的区域，请先设置省市区信息');
        }

    }

    /**
     * 根据市名字获取区数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Exception
     * @throws \Lybc\PhpGB2260\InvalidCodeException
     *
     * create by qgz 20180808
     */
    public function getCountryDataByCityAction()
    {
        $provId = $this->request->getPost('provId');
        $cityId = $this->request->getPost('cityId');
        if (empty($provId) || empty($cityId)) {
            return $this->sendJsonResponse(['' => '-请选择区-']);
        }
        $isCQ = false;
        if ($provId == '重庆市') {//重庆市的话加上丰都县，姚超让加的
            $isCQ = true;
        }
        $id = '';
        $areaObj = new Area();
        $provArr = $areaObj->getAllProvinces(true);
        foreach ($provArr as $key => $item) {
            if ($item == $provId) {
                $id = $key;
                break;
            }
        }
        $return = [];
        try {
            $areaObj = new Area((int)$id);
            $allCity = $areaObj->getCity();
            foreach ($allCity as $item => $value) {
                if ($value == $cityId) {
                    $id = $item;
                    break;
                }
            }
            $areaObj = new Area((int)$id);
            $allDistrict = $areaObj->getDistrict();
            if ($isCQ) {
                $allDistrict[500230] = '丰都县';
            }
            foreach ($allDistrict as $value) {
                $return[$value] = $value;
            }
            $return = ['' => '-请选择区-'] + $return;
            return $this->sendJsonResponse($return);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(400, '学校还没有设置所属的区域，请先设置省市区信息');
        }
    }

    /**
     * 根据学校id检查是否已存在此ID
     *
     * @return string
     *
     * create by ck 20160819
     * modify by ck 20171115
     */
    public function checkSchoolIdValidAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        if (!$schoolId) {
            return $this->sendErrorResponse(400, '缺少学校id', null, false);
        }
        if (XhschoolInfo::count($schoolId)) {
            return $this->sendErrorResponse(400, '学校id已存在', null, false);
        }
        return $this->sendSuccessResponse('该学校id可用');
    }

    /**
     * 根据传入id字符串删除相应记录
     *
     * create by ck 20160304
     * modify by ck 20160621    优化
     * modify by ck 20171115    更改结构
     */
    public function delDataAction()
    {
        if (!Power::exist('School_List_Del')) {
            return $this->sendErrorResponse(403, '缺少删除权限');
        }
        $ids = $this->request->getPost('ids');
        if (!XhschoolInfo::deleteRecord('iSchoolId', $ids)) {
            return $this->sendErrorResponse(500, '删除失败');
        }
        School::refresh();
        return $this->sendSuccessResponse('删除成功');
    }

    /**
     * 学校-学生列表页面
     *
     * create by ck 20160318
     * modify by ck 20160621
     */
    public function schoolStudentListAction()
    {
        $this->view->pick('school/schoolStudentList');
        Assets::easyUI('js/school/schoolStudentList.js');
        Main::showNavPosition();
        Power::exist('School_StudentList') or die(Main::showMessageModal('对不起，您没有查看此页面的权限！', 109106007));
        Template::exists('XHSchool_Info', 'list') && Template::exists('XHSys_User', 'list')
        or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106008));
        $schSearchArr[] = array('type' => 'text', 'id' => 'SchoolList_Search', 'label' => '搜索： ');
        $schSearchToolbar = Template::createSearchToolBar($schSearchArr);
//        $stuSearchArr[] = [
//            'label' => ' 缴费凭证 : ',
//            'type' => 'select',
//            'id' => 'StuList_Search',
//            'data' => [0 => '全部'] + [1 => '未上传', 2 => '已上传'] ,
//            'style' => 'margin-left:10px;width:80px;'
//        ];
//        $stuSearchToolbar = Template::createSearchToolBar($stuSearchArr);
        $this->view->setVars(array(
            'SchoolList' => Template::createList('SchoolList', 'XHSchool_Info', array(
                'searchToolbar' => $schSearchToolbar,
                'checkbox' => false,
                'field' => array('iSchoolId', 'sSchoolName'),
                'tableAttr' => array(
                    'singleSelect' => 'true'
                )
            )),
            'StudentList' => Template::createList('StudentList', 'XHSys_User', array(
//                'searchToolbar' => $stuSearchToolbar,
                'checkbox' => false,
                'field' => array('iUserId', 'sUserName', 'iUserSex', 'sLogonName', 'sAdClsName'),
                'tableAttr' => array(
                    'singleSelect' => 'true'
                )
            ))
        ));
    }

    /**
     * 学校-教师列表页面
     *
     * create by ck 20160318
     * modify by ck 20160621    优化
     * modify by ck 20160815    优化
     * modify by ck 20160927    js压缩，搜索添加
     * modify by dale 20181011   重要老师优秀老师
     */
    public function schoolTeacherListAction()
    {
        $this->view->pick('school/schoolTeacherList');
        Assets::datetimePicker();
        Assets::easyUI('js/school/schoolTeacherList.js');
        Assets::importMainJs('assets/easyui/datagrid-detailview.js');
        Main::showNavPosition();
        Power::exist('School_TeacherList') or die(Main::showMessageModal('对不起，您没有查看此页面的权限！', 109106009));
        Template::exists('XHSchool_Info', 'list') && Template::exists('School_TeacherList', 'list')
        or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106010));
        $tchListButtonArr = $tchSearchArr = $schSearchArr = [];
        if (Power::exist('School_TeacherList_OpenClass')) {
//            $tchListButtonArr[] = ['plain'=>'true', 'id'=>'bt_list_OpenClass', 'text'=>'开课', 'icon'=>'fa-folder-open-o'];
            $tchListButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_ViewClass', 'text' => '查看', 'icon' => 'fa-eye'];
        }
        $iStatus = [
            '' => '状态',
            1 => '上线',
            2 => '运营',
        ];
        $schSearchArr[] = array('type' => 'select', 'id' => 'list_search_status', 'data' => $iStatus);
        $schSearchArr[] = ['type' => 'text', 'id' => 'SchoolList_Search', 'style' => 'width:100px;', 'label' => ' '];
        $schSearchArr[] = ['type' => 'button', 'id' => 'bt_SchoolList_Search', 'text' => '确定', 'icon' => 'fa-search', 'style' => 'margin-left:5px'];
        $schSearchArr[] = ['type' => 'button', 'id' => 'bt_SchoolList_Time', 'icon' => 'fa-binoculars', 'text' => '更多', 'style' => 'margin-left:5px'];

        $enum = [
            1 => '全部',
            2 => '无更新',
            3 => '有更新',
        ];
        $tchLog = ['' => '更新内容', 1 => '基本信息', 2 => '教师日志', 3 => '公开课', 4 => '公开课反馈'];
        $subject = XhsysEnum::getEnumByNodeName('学科');
        $subject[''] = '学科';
        $history = [
            1 => '历史',
            0 => '正常',
        ];
        $grade = XhsysEnum::getEnumByNodeName('年级');
        $grade[''] = '年级';
        $select_trackType = XhsysEnum::getEnumByNodeName('教师跟踪类型');
        $select_trackType[''] = '日志类型';
        $tchSearchArr[] = array('type' => 'select', 'id' => 'select_history', 'data' => $history, 'default' => 0, 'style' => 'width:60px;');
        $tchSearchArr[] = array('type' => 'select', 'id' => 'select_trackType', 'data' => $select_trackType, 'default' => '');
        $tchSearchArr[] = array('type' => 'select', 'id' => 'select_type', 'data' => $enum, 'default' => 1);
        $tchSearchArr[] = array('type' => 'select', 'id' => 'select_log', 'data' => $tchLog, 'default' => '');
        $tchSearchArr[] = array('type' => 'select', 'id' => 'select_subject', 'data' => $subject, 'default' => '', 'style' => 'width:60px;');
        $tchSearchArr[] = array('type' => 'select', 'id' => 'select_grade', 'data' => $grade, 'default' => '');
        $tchSearchArr[] = array('type' => 'select', 'id' => 'select_important', 'data' => self::$tchEnum['bImportant'], 'default' => '0');
        $tchSearchArr[] = array('type' => 'select', 'id' => 'select_excellent', 'data' => self::$tchEnum['bExcellent'], 'default' => '0');
        $tchSearchArr[] = array('type' => 'text', 'id' => 'List_Search_StartTime', 'label' => ' 时间：', 'class' => 'easyui-datebox', 'style' => 'width:100px !important ;');
        $tchSearchArr[] = array('type' => 'text', 'id' => 'List_Search_EndTime', 'label' => ' ~', 'class' => 'easyui-datebox', 'style' => 'width:100px !important ;');
        $tchSearchArr[] = ['type' => 'text', 'id' => 'TeacherList_Search', 'label' => ' ', 'style' => 'width:100px;'];
        $tchSearchArr[] = ['type' => 'button', 'id' => 'bt_TeacherList_Search', 'text' => '确定', 'icon' => 'fa-search', 'style' => 'margin-left:10px'];
//        $tchButtonToolbar = Template::createButtonToolBar($tchListButtonArr);
//        $schSearchToolbar = Template::createSearchToolBar($schSearchArr);
        $this->view->setVars([
            'SchoolList' => Template::createList('SchoolList', 'XHSchool_Info', [
                'searchToolbar' => Template::createSearchToolBar($schSearchArr),
                'checkbox' => false,
                'field' => ['iSchoolId', 'sSchoolName'],
                'tableAttr' => ['singleSelect' => 'true']
            ]),
            'TeacherList' => Template::createList('TeacherList', 'School_TeacherList', [
                'checkbox' => false,
                'searchToolbar' => Template::createSearchToolBar($tchSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($tchListButtonArr),
                'field' => ['tchIcon', 'iUserId', 'sUserName', 'iUserSex', 'sLogonName', 'tTime', 'sSchoolName', 'iCurGrade', 'iSubject', 'iProficiency'],
                'tableAttr' => ['singleSelect' => 'true']
            ])
        ]);
    }


    /**
     * 修改年级
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181203
     */
    public function setCurGradeAction()
    {
        $tchIds = $this->request->getPost('tchIds', 'string');
        $grade = $this->request->getPost('currentGrade', 'string');
        if (!$tchIds || !$grade) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        if (!is_array($tchIds)) {
            return $this->sendErrorResponse(400, '格式不匹配');
        }
        try {
            $tchObjArr = XhsysUserTch::find([
                'conditions' => 'bDelete = 0 and iUserId in ({ids:array}) ',
                'bind' => ['ids' => $tchIds]
            ]);
            if ($tchObjArr->toArray()) {
                $this->db->begin();
                foreach ($tchObjArr as $tchObj) {
                    $tchObj->iCurGrade = $grade;
                    if (!$tchObj->save()) {
                        throw new XhException('保存失败');
                    }
                }
                $this->db->commit();
            }
            return $this->sendSuccessResponse('修改成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 选择应用页面
     *
     * create by ck 20160323
     * modify by ck 20160927    js压缩
     */
//    public function schoolChooseAppAction()
//    {
//        $this->view->pick('school/schoolChooseApp');
//        Assets::easyUI('js/school/schoolChooseApp.js');
//        $this->view->setVar('AppList', Template::createList('AppList', 'XHApp_Store',
//            array(
//                'checkbox' => false,
//                'tableAttr' => array(
//                    'singleSelect'  => true
//                )
//            )
//        ));
//    }

    /**
     * 学校相关设置页面
     *
     * create by ck 20160622
     * modify by ck 20161011
     * modify by ck 20161011    添加权限
     */
    public function schoolSettingAction()
    {
        $this->view->pick('school/schoolSetting');
        Assets::importJs('js/school/schoolSetting.js');
        $schoolId = $this->request->getQuery('iSchoolId', 'int');
        $schoolName = $this->request->getQuery('sSchoolName', 'string');
        if (!School::hasPower($schoolId)) {
            return $this->sendViewError('无该学校查看权限！');
        }
        $urlArgs = ['iSchoolId' => $schoolId, 'sSchoolName' => $schoolName];
        $powerTags = [
//            'School_List_Class' => [
//                'name' => '班级管理',
//                'url' => $this->url->get('School/schoolClassManageList', $urlArgs),
//                'class' => 'default'
//            ],
            'School_List_Stud' => [
                'name' => '学生管理',
                'url' => $this->url->get('School/student', $urlArgs),
                'class' => 'success'
            ],
            'School_List_Tch' => [
                'name' => '教师管理',
                'url' => $this->url->get('School/teacher', $urlArgs),
                'class' => 'danger'
            ],
            'School_List_Group' => [
                'name' => '应用组管理',
                'url' => $this->url->get('Appgroup/appGroup', ['schoolId' => $schoolId]),
                'class' => 'success'
            ],
            'School_List_Manage' => [
                'name' => '学校管理',
                'url' => $this->url->get('School/schoolManage', ['schoolId' => $schoolId, 'direction' => 'school']),
                'class' => 'default'
            ],
            'School_List_App' => [
                'name' => '应用管理',
                'url' => $this->url->get('Appserver/schoolApp', ['schoolId' => $schoolId]),
                'class' => 'danger'
            ],
            'School_List_QBank' => [
                'name' => '题库管理',
                'url' => $this->url->get('School/schoolContactQBank', $urlArgs),
                'class' => 'default'
            ],
            'School_List_OtherUser' => [
                'name' => '其他用户',
                'url' => $this->url->get('School/otherUser', ['schoolId' => $schoolId]),
                'class' => 'default'
            ],
            'School_List_BrushGroup' => [
                'name' => '刷题王分组',
                'url' => $this->url->get('stats_brush/brushGroup', ['schoolId' => $schoolId]),
                'class' => 'success'
            ],
            'School_List_Books' => [
                'name' => '校本库',
                'url' => $this->url->get('School/schoolManage', ['schoolId' => $schoolId, 'view' => 'partial', 'direction' => 'Question-index']),
                'class' => 'success'
            ],
//            'School_List_TchManage' => [
//                'name'  => '教师管理后台',
//                'url'   => $this->url->get('School/schoolManage', ['schoolId' => $schoolId, 'direction' => 'teacher']),
//                'class' => 'danger'
//            ],
//            'School_List_Old' => [
//                'name' => '老后台',
//                'url' => $this->url->get('School/redirectOldSchool', ['schoolId' => $schoolId]),
//                'class' => 'danger',
//                'target' => '_blank'
//            ],
        ];
        $schoolPowerTags = [];
        foreach ($powerTags as $powerTag => $powerInfo) {
            if (Power::exist($powerTag)) {
                $schoolPowerTags[$powerTag] = $powerInfo;
            }
        }
        return $this->view->setVars([
//            'schoolId'     => $schoolId,
            'schoolName' => $schoolName,
            'schoolPowerTags' => $schoolPowerTags
        ]);
    }

    /**
     * 学校应用管理页面
     *
     * create by ck 20160622
     * modify by ck 20160913    更改结构
     * modify by ck 20161011    添加权限
     *
     */
    public function schoolAppListAction()
    {
        $this->view->pick('school/schoolAppList');
        Assets::easyUI('js/school/schoolAppList.js');
        $schoolId = $this->request->getQuery('iSchoolId', 'int');
        Template::exists('XHSchool_AppStore', 'list') or die(Main::showMessageModal('应用列表配置文件不存在，请先创建！', true));
        School::hasPower($schoolId) or die(Main::showMessageModal('无查看权限！', 109106038));
        $listButtonArr = [];
        if (School::hasPower($schoolId, true)) {
            $listButtonArr[] = ['id' => 'bt_list_add', 'text' => '增加', 'plain' => 'true', 'icon' => 'fa-plus'];
            $listButtonArr[] = ['id' => 'bt_list_del', 'text' => '删除', 'plain' => 'true', 'icon' => 'fa-trash'];
            $listButtonArr[] = ['id' => 'bt_list_Update', 'text' => '更新', 'plain' => 'true', 'icon' => 'fa-refresh'];
            $listButtonArr[] = ['id' => 'bt_list_UpdateAll', 'text' => '更新全部', 'plain' => 'true', 'icon' => 'fa-refresh'];
            $listButtonArr[] = ['id' => 'bt_list_enable', 'text' => '启用', 'plain' => 'true', 'icon' => 'fa-chain'];
            $listButtonArr[] = ['id' => 'bt_list_disable', 'text' => '禁用', 'plain' => 'true', 'icon' => 'fa-chain-broken'];
            $listButtonArr[] = ['id' => 'bt_list_DownEnable', 'text' => '启用下载', 'plain' => 'true', 'icon' => 'fa-chain'];
            $listButtonArr[] = ['id' => 'bt_list_DownDisable', 'text' => '禁用下载', 'plain' => 'true', 'icon' => 'fa-chain-broken'];
        }
        $buttonToolbar = Template::createButtonToolBar($listButtonArr);
        $this->view->setVars([
            'sSchoolName' => $this->request->getQuery('sSchoolName', 'string'),
            'List' => Template::createList('List', 'XHSchool_AppStore', ['buttonToolbar' => $buttonToolbar])
        ]);
    }

    /**
     * 获取学校绑定的应用
     *
     * create by ck 20160623
     * modify by ck 20160928    查询条件更改
     */
    public function getAppDgDataAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $schoolId = $this->request->getPost('iSchoolId', 'int', 0);
        $type = $this->request->getPost('type', 'string');
        if ($type == 'in') {
            $builder = XhschoolAppstore::createBuilderForInAppInfoBySchoolId($schoolId);
            echo Main::runBuilderPaginator($builder);
        } elseif ($type == 'out') {
            $queryArr = XhschoolAppstore::createPhqlForOutAppInfoBySchoolId($schoolId);
            echo Main::runPhqlPaginator($queryArr);
        } elseif ($type == 'version') {
            $appCode = $this->request->getPost('iAppCode', 'string');
            $parameters = array(
                'conditions' => "bDelete = 0 AND iAppCode = '{$appCode}'",
                'order' => 'sAppVersion DESC'
            );
            echo Main::runModelPaginator('\\Admin\\Models\\app\\XhappStore', $parameters);
        }
    }

    /**
     * 根据id删除学校应用关联
     *
     * create by ck 20160624
     * modify by ck 20160928
     * modify by ck 20161011    添加权限
     */
    public function delSchoolAppAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        School::hasPower($this->request->getQuery('iSchoolId', 'int'), true)
        or die(Main::showMessageModal('无管理权限！', 109106039));
        $ids = explode(',', $this->request->getPost('ids'));
        XhschoolAppstore::deleteRecordById($ids) or die('（109106011）删除失败');
        echo '删除成功！';
        Main::createCommitLog('school', 'SchoolAppStore', 'del', ['ids' => $ids], null, '批量删除');
    }

    /**
     * 不存在于学校的应用及版本列表页面
     *
     * create by ck 20160624
     * modify by ck 20160913    结构更改
     * modify by ck 20160928    js压缩
     * modify by ck 20161011    添加权限
     */
    public function schoolOutAppListAction()
    {
        $this->view->pick('school/schoolOutAppList');
        Assets::easyUI('js/school/schoolOutAppList.js');
        Template::exists('XHApp_Store', 'list') or die(Main::showMessageModal('列表配置文件不存在，请先创建！', 109106012));
        School::hasPower($this->request->getQuery('iSchoolId', 'int'))
        or die(Main::showMessageModal('无查看权限！', 109106040));
        $this->view->setVars(array(
            'SchoolAppOutList' => Template::createList('SchoolOutAppList', 'XHApp_Store',
                array(
                    'checkbox' => false,
                    'tableAttr' => array('singleSelect' => 'true'),
                    'field' => array('iAppId', 'iAppCode', 'sAppName', 'iAppType', 'sAppPackage', 'iAppSystem')
                )),
            'SchoolAppVersionList' => Template::createList('SchoolAppVersionList', 'XHApp_Store',
                array(
                    'checkbox' => false,
                    'tableAttr' => array('singleSelect' => 'true'),
                    'field' => array('iAppId', 'sAppVersion')
                )),
        ));
    }

    /**
     * 根据学校ID和应用ID关联
     *
     * create by ck 20160627
     * modify by ck 20161011    添加权限
     */
    public function contactSchoolAppAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $appId = $this->request->getPost('iAppId');
        $schoolId = $this->request->getPost('iSchoolId');
        School::hasPower($schoolId, true)
        or die(Main::showMessageModal('无管理权限！', 109106040));
        $contact = XhschoolAppstore::createRecord($schoolId, $appId);
        $contact->insertData() or die(Main::showMessageModal('关联失败！', 109106013));
        echo 1;
        Main::createCommitLog('school', 'SchoolAppStore', 'add', $contact, $contact->iSASId);
    }

    /**
     * 学校题库关联页面
     *
     * create by ck 20160622
     * modify by ck 20160913    结构更改
     * modify by ck 20160924    结构更改
     * modify by ck 20170410    去除应用选择页面，使用下拉框
     */
    public function schoolContactQBankAction()
    {
        $this->view->pick('school/schoolContactQBank');
        $schoolId = $this->request->getQuery('iSchoolId', 'int');
        School::hasPower($schoolId) or die(Main::showMessageModal('无查看权限！', 109106054));
        if (!Power::exist('School_List_QBank')) {
            return $this->sendViewError('无教师管理权限！');
        }
        Assets::easyUI('js/school/schoolContactQBank.js');
        Assets::select2();
        $this->view->setVars(array(
            'nav' => $this->request->getQuery('nav', 'string'),
            'schoolName' => $this->request->getQuery('sSchoolName', 'string'),
            'appCode' => XhsysEnum::getEnumByNodeName('应用编号'),
            'InList' => Template::createList('InList', 'XHRes_QuestionBank', array('title' => '已关联题库')),
            'NotList' => Template::createList('OutList', 'XHRes_QuestionBank', array('title' => '未关联题库')),
        ));
    }

    /**
     * 更新应用版本到最新
     *
     * create by ck 20160627
     * modify by ck 20160630    更新，不标记删除
     * modify by ck 20160928    修正sql语句错误
     * modify by ck 20161011    添加权限
     */
    public function updateSchoolAppAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $SASIds = $this->request->getPost('sSASId', 'string');
        $schoolId = $this->request->getPost('iSchoolId', 'int');
        $SASIds && $schoolId or die(Main::showMessageModal('无更新条件', 109106014));
        School::hasPower($schoolId, true)
        or die(Main::showMessageModal('无管理权限！', 109106041));
        (!empty(explode(',', $SASIds)) || $SASIds == 'all') or die(Main::showMessageModal('参数错误！', 109106015));
        XhschoolAppstore::updateSchoolAppBySchoolId($schoolId, $SASIds) or die(Main::showMessageModal('更新失败！', 109106016));
        echo 1;
        if ($SASIds == 'all') Main::createCommitLog('school', 'SchoolAppStore', 'updateAll', ['iSchoolId' => $schoolId], null, '全部更新');
        else Main::createCommitLog('school', 'SchoolAppStore', 'update', ['ids' => explode(',', $SASIds)], null, '全部更新');
    }

    /**
     * 设置学校应用状态（启用/禁用）
     *
     * create by ck 20160628
     * modify by ck 20161011    添加权限
     */
    public function setSchoolAppStateAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $schoolId = $this->request->getQuery('iSchoolId', 'int');
        School::hasPower($schoolId, true)
        or die(Main::showMessageModal('无管理权限！', 109106042));
        $schoolAppIds = $this->request->getPost('sSASId');
        $target = $this->request->getPost('target');
        switch ($target) {
            case 'enable':
                $sqlParamStr = "bSASEnable = 1";
                break;
            case 'disable':
                $sqlParamStr = "bSASEnable = 0";
                break;
            case 'downEnable':
                $sqlParamStr = "bSASDown   = 1";
                break;
            case 'downDisable':
                $sqlParamStr = "bSASDown   = 0";
                break;
            default:
                die('（109106017）无此操作类型');
        }
        $sqlStr = "UPDATE Admin\Models\school\XhschoolAppstore SET {$sqlParamStr} WHERE iSASId IN ({$schoolAppIds})";
        $query = $this->modelsManager->executeQuery($sqlStr);
        $query or die('（109106018）操作失败');
        echo '操作成功';
        Main::createCommitLog('school', 'SchoolAppStore', 'edit', array('iSASId' => $schoolAppIds, 'type' => $target));
    }

    /**
     * 学校应用组页面
     *
     * create by ck 20160630
     * modify by ck 20160913    结构更改
     * modify by ck 20161011    添加权限
     */
    public function schoolAppGroupAction()
    {
        $this->view->pick('school/schoolAppGroup');
        Assets::easyUI('js/school/schoolAppGroup.js');
        Template::exists('XHSchool_AppGroup', 'both') or die(Main::showMessageModal('列表配置文件不存在，请先创建！', 109106019));
        $schoolId = $this->request->getQuery('iSchoolId', 'int');
        School::hasPower($schoolId) or die(Main::showMessageModal('无查看权限！', 109106043));
        $listButtonArr = $formButtonArr = array();
        if (School::hasPower($schoolId, true)) {
            $listButtonArr[] = array('id' => 'bt_list_add', 'text' => '增加', 'plain' => 'true', 'icon' => 'fa-plus');
            $listButtonArr[] = array('id' => 'bt_list_del', 'text' => '删除', 'plain' => 'true', 'icon' => 'fa-trash');
            $listButtonArr[] = array('id' => 'bt_list_enable', 'text' => '启用', 'plain' => 'true', 'icon' => 'fa-chain');
            $listButtonArr[] = array('id' => 'bt_list_disable', 'text' => '禁用', 'plain' => 'true', 'icon' => 'fa-chain-broken');
            $listButtonArr[] = array('id' => 'bt_list_addStudent', 'text' => '添加学生', 'plain' => 'true', 'icon' => 'fa-plus');
            $listButtonArr[] = array('id' => 'bt_list_addTeacher', 'text' => '添加教师', 'plain' => 'true', 'icon' => 'fa-plus');
            $listButtonArr[] = array('id' => 'bt_list_SetAppStore', 'text' => '设置应用', 'plain' => 'true', 'icon' => 'fa-pencil');
            $formButtonArr[] = array('id' => 'bt_form_add', 'text' => '增加', 'class' => 'disabled');
            $formButtonArr[] = array('id' => 'bt_form_edit', 'text' => '修改', 'class' => 'disabled');
            $formButtonArr[] = array('id' => 'bt_form_back', 'text' => '返回');
            $formButtonArr[] = array('id' => 'bt_form_reset', 'text' => '重置');
        }
        $buttonToolbar = Template::createButtonToolBar($listButtonArr);
        $this->view->setVars(array(
            'sSchoolName' => $this->request->getQuery('sSchoolName', 'string'),
            'List' => Template::createList('List', 'XHSchool_AppGroup', [
                'buttonToolbar' => $buttonToolbar,
                'field' => ['iSAGId', 'sSAGName', 'iSAType', 'bSAGEnable']
            ]),
            'Form' => Template::createForm('XHSchool_AppGroup'),
            'FormButton' => Template::createButtonToolBar($formButtonArr)
        ));
    }

    /**
     * 获取学校应用组
     *
     * create by ck 20160701
     * modify by ck 20160930    分页方法更改
     */
    public function getGroupDgDataAction()
    {
        $this->view->disable();
        $schoolId = $this->request->getPost('iSchoolId');
        $parameters = ['conditions' => "bDelete = 0 AND iSchoolId = {$schoolId}"];
        echo Main::runModelPaginator('\\Admin\\Models\\school\\XhschoolAppgroup', $parameters);
    }

    /**
     * 新增/修改学校应用组信息
     *
     * create by ck 20160701
     * modify by ck 20160930
     */
    public function modifyGroupDataAction()
    {
        $this->view->disable();
        School::hasPower($this->request->getQuery('iSchoolId', 'int'))
        or die(Main::showMessageModal('无管理权限！', 109106044));
        $realData = Main::getRealData($this->request->getPost());
        $obj = XhschoolAppgroup::createRecord($realData);
        if ($obj->iSAGId) {
            $obj->updateData() or die(Main::showMessageModal('修改失败！', 109106020));
            Main::createCommitLog('school', 'SchoolAppGroup', 'edit', $obj, $obj->iSAGId);
        } else {
            $obj->insertData() or die(Main::showMessageModal('新增失败！', 109106021));
            Main::createCommitLog('school', 'SchoolAppGroup', 'add', $obj, $obj->iSAGId);
        }
    }

    /**
     * 根据id删除学校应用关联
     *
     * create by ck 20160624
     * modify by ck 20160930    优化
     */
    public function delSchoolGroupDataAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        School::hasPower($this->request->getQuery('iSchoolId', 'int'), true)
        or die(Main::showMessageModal('无管理权限！', 109106045));
        $idArr = explode(',', $this->request->getPost('ids'));
        XhschoolAppgroup::deleteRecordById($idArr) or die('（109106022）删除失败！');
        echo '删除成功！';
        Main::createCommitLog('school', 'SchoolAppGroup', 'del', ['ids' => $idArr], null, '批量删除');
    }

    /**
     * 设置应用组启用/禁用
     *
     * create by ck 20160701
     */
    public function setSchoolGroupStateAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        School::hasPower($this->request->getQuery('iSchoolId', 'int'), true)
        or die(Main::showMessageModal('无管理权限！', 109106046));
        $ids = $this->request->getPost('ids', 'string');
        $target = $this->request->getPost('target', 'string');
        switch ($target) {
            case 'enable':
                $sqlParamStr = 'bSAGEnable = 1';
                break;
            case 'disable':
                $sqlParamStr = 'bSAGEnable = 0';
                break;
            default:
                die('（109106023）无此操作类型');
        }
        $sql_str = "UPDATE \\Admin\\Models\\school\\XhschoolAppgroup SET $sqlParamStr WHERE iSAGId IN ($ids)";
        $query = $this->modelsManager->executeQuery($sql_str);
        $query or die('（109106024）操作失败');
        Main::createCommitLog('school', 'SchoolAppStore', $target, ['iSAGId' => $ids]);
        echo '操作成功';
    }

    /**
     * 未分配应用组的学校教师列表页面
     *
     * create by ck 20160704
     * modify by ck 20160913    结构更改
     * modify by ck 20160930    js压缩
     */
    public function schoolOutGroupTeacherListAction()
    {
        $this->view->pick('school/schoolOutGroupTeacherList');
        Assets::easyUI('js/school/schoolOutGroupTeacherList.js');
        Template::exists('XHSys_User', 'list') or die(Main::showMessageModal('列表配置文件不存在，请先创建！', 109106025));
        School::hasPower($this->request->getQuery('iSchoolId', 'int'))
        or die(Main::showMessageModal('无查看权限！', 109106047));
        $this->view->setVars([
            'List' => Template::createList('List', 'XHSys_User', [
                'field' => ['iUserId', 'sUserName', 'sLogonName', 'iUserSex']
            ])
        ]);
    }

    /**
     * 未分配应用组的学校学生列表页面
     *
     * create by ck 20160704
     * modify by ck 20160930    js压缩
     */
    public function schoolOutGroupStudentListAction()
    {
        $this->view->pick('school/schoolOutGroupStudentList');
        Assets::easyUI('js/school/schoolOutGroupStudentList.js');
        Template::exists('XHSys_User', 'list') or die(Main::showMessageModal('列表配置文件不存在，请先创建！', 109106026));
        School::hasPower($this->request->getQuery('iSchoolId', 'int'))
        or die(Main::showMessageModal('无查看权限！', 109106048));
        $this->view->setVars([
            'List' => Template::createList('List', 'XHSys_User', [
                'field' => ['iUserId', 'sUserName', 'sLogonName', 'iUserSex']
            ])
        ]);
    }

    /**
     * 获取未加入应用组的学校用户列表
     *
     * create by ck 20160704
     * modify by ck 20160930    sql语句更改
     */
    public function getOutGroupUserDgDataAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $schoolId = $this->request->getPost('iSchoolId', 'int');
        $userType = $this->request->getPost('iUserType', 'int');
        $groupId = $this->request->getPost('iSAGId', 'int');
        $schoolId && $userType && $groupId or die;
        $queryArr = XhschoolUserappgroup::createSqlForOutUserByGroupId($schoolId, $userType, $groupId);
        echo Main::runSqlPaginator($queryArr);
    }

    /**
     * 学校应用组关联用户
     *
     * create by ck 20160704
     * modify by ck 20160930    批量插入更改，提高效率
     */
    public function contactGroupUserAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $schoolId = $this->request->getPost('iSchoolId');
        $groupId = $this->request->getPost('iSAGId');
        School::hasPower($schoolId, true)
        or die(Main::showMessageModal('无管理权限！', 109106049));
        $userIds = explode(',', $this->request->getPost('ids'));
        $this->db->begin();
        XhschoolUserappgroup::deleteRecordById($userIds) or die('（109106027）删除原记录失败！');
        if (!XhschoolUserappgroup::batchCreateUserInGroup($userIds, $schoolId, $groupId)) {
            $this->db->rollback();
            die('添加失败！');
        }
        $this->db->commit();
        echo '添加成功！';
        Main::createCommitLog('school', 'SchoolUserAppGroup', 'add', ['ids' => $userIds, 'iSAGId' => $groupId], null, '批量添加');
    }

    /**
     * 学校应用组设置应用页面
     *
     * create by ck 20160704
     * modify by ck 20160930    js压缩
     */
    public function schoolGroupAppListAction()
    {
        $this->view->pick('school/schoolGroupAppList');
        Assets::easyUI('js/school/schoolGroupAppList.js');
        Template::exists('XHApp_Store', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106029));
        School::hasPower($this->request->getQuery('iSchoolId', 'int'))
        or die(Main::showMessageModal('无查看权限！', 109106050));
        $field = ['iSASId', 'iAppId', 'iAppCode', 'sAppName', 'iAppType', 'sAppPackage', 'iAppSystem'];
        $this->view->setVars(array(
            'GroupInAppList' => Template::createList('InList', 'XHSchool_AppStore', ['title' => '已关联应用', 'field' => $field]),
            'GroupOutAppList' => Template::createList('OutList', 'XHSchool_AppStore', ['title' => '未关联应用', 'field' => $field])
        ));
    }

    /**
     * 根据学校ID，应用组ID，类型获取相关应用信息
     *
     * create by ck 20160704
     * modify by ck 20160705    增加SchoolAppStoreId显示
     * modify by ck 20160930    sql语句更改
     */
    public function getGroupAppDgDataAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $schoolId = $this->request->getPost('iSchoolId', 'int');
        $groupId = $this->request->getPost('iSAGId', 'int');
        $type = $this->request->getPost('type', 'string');
        $queryArr = XhschoolAppgroupapp::createSqlForAppInfoByGroupId($groupId, $type, $schoolId);
        echo Main::runSqlPaginator($queryArr);
    }

    /**
     * 关联学校应用组应用
     *
     * create by ck 20160705
     * modify by ck 20161008    关联改为批量插入
     */
    public function contactGroupSchoolAppAction()
    {
        $this->view->disable();
        $this->request->isPost() or die;
        $schoolId = $this->request->getPost('iSchoolId', 'int');
        $groupId = $this->request->getPost('iSAGId', 'int');
        $type = $this->request->getPost('type', 'string');
        $ids = $this->request->getPost('ids', 'string');
        $schoolId && $groupId && $type && $ids or die(Main::showMessageModal('参数错误！', 109106030));
        School::hasPower($schoolId, true)
        or die(Main::showMessageModal('无管理权限！', 109106051));
        $schAppIdArr = explode(',', $ids);
        !empty($schAppIdArr) or die(Main::showMessageModal('学校应用ID不能为空！', 109106031));
        if ($type == 'in') {
            XhschoolAppgroupapp::contactSchoolGroupApp($schAppIdArr, $groupId, $schoolId)
            or die(Main::showMessageModal('关联失败！', 109106032));
            Main::createCommitLog('school', 'SchoolAppGroupApp', 'add', ['ids' => $schAppIdArr, 'iSAGId' => $groupId, 'iSchoolId' => $schoolId]);
        } else {
            XhschoolAppgroupapp::deleteSchoolGroupApp($schAppIdArr, $groupId, $schoolId)
            or die(Main::showMessageModal('取消关联失败！', 109106033));
            Main::createCommitLog('school', 'SchoolAppGroupApp', 'del', ['ids' => $schAppIdArr, 'iSAGId' => $groupId, 'iSchoolId' => $schoolId]);
        }
        echo 'success';
    }

    /**
     * 学校学生管理页面（单学校管理）
     *
     * create by ck 20160706
     * modify by ck 20160913    结构更改
     * modify by ck 20161008    js集合
     * modify by ck 20170927    结构更改
     * modify by ck 20171129    添加班级列表，可筛选
     * modify by ck 20180604    设备绑定多位用户添加学校控制
     * modify by ck 20180711    手动设备绑定
     * modify by zqk 20181116    上传缴费凭证
     */
    public function studentAction()
    {
        $this->view->pick('school/student');
        Main::showNavPosition('学校列表', ['学校设置', '学生管理'], true);
        Assets::easyUI('js/school/student.js');
        Assets::importMainJs('assets/jquery/jquery.fileDownload.js');
        $schoolId = $this->request->getQuery('iSchoolId', 'int');
        if (!School::hasPower($schoolId)) {
            return $this->sendViewError('无该学校查看权限');
        }
        if (!Power::exist('School_List_Stud')) {
            return $this->sendViewError('无学生管理权限！');
        }
        $listSearchArr = $listButtonArr = $formButtonArr = array();
        $managePower = School::hasPower($schoolId, true);
        $power = [
            'spare' => false,
            'auth' => false,
            'bind' => false,
            'handBind' => false,
            'repair' => false,
            'edit' => false,
            'studNo' => false,
            'identity' => false,
            'add' => false,
            'unbind' => false,
            'group' => false,
            'assist' => false,
            'random' => false,
//            'configureList' => false
        ];
        if ($managePower) {
            $listButtonArr[] = ['id' => 'bt_list_refresh_login', 'text' => '刷新登陆', 'plain' => 'true', 'icon' => 'fa-refresh'];
            if (Power::exist('School_List_Stud_Pwd')) {
                $listButtonArr[] = ['id' => 'bt_list_set_pwd', 'text' => '修改密码', 'plain' => 'true', 'icon' => 'fa-pencil'];
            }
            if (Power::exist('School_List_Stud_Login')) {
                $listButtonArr[] = ['id' => 'bt_list_login', 'text' => '扫码登陆', 'plain' => 'true', 'icon' => 'fa-tablet'];
            }
            $listButtonArr[] = ['id' => 'bt_list_tablet', 'class' => 'menubutton', 'text' => '机器使用', 'plain' => 'true', 'icon' => 'fa-tablet'];
            $power['spare'] = Power::exist('School_List_Spare');
            $power['handBind'] = Power::exist('School_List_Stud_HandBind');
            if (Power::exist('School_List_Stud_Auth')) {
                $ips = Tool::getValue(Main::getConfigByName('admin'), 'companyIP', [], function ($ips) {
                    return explode(';', $ips);
                });
                if (empty($ips) || in_array(Tool::getIp(), $ips)) {
                    $power['auth'] = true;
                }
            }
            if (Power::exist('School_List_Stud_Bind')) {
                $allowSchoolIds = Tool::getValue(Main::getConfigByName('admin'), 'bindDevSchoolIds', [], function ($allowSchoolIds) {
                    return explode('|', $allowSchoolIds);
                });
                if (in_array($schoolId, $allowSchoolIds)) {
                    $power['bind'] = true;
                }
            }
            $listButtonArr[] = ['id' => 'bt_list_apply', 'class' => 'menubutton', 'text' => '申请', 'plain' => 'true', 'icon' => 'fa-pencil'];
            $power['repair'] = Power::exist('School_List_Stud_Repair');
            $listButtonArr[] = ['id' => 'bt_list_setting', 'class' => 'menubutton', 'text' => '设置', 'plain' => 'true', 'icon' => 'fa-cog'];
            $power['edit'] = Power::exist('School_List_Stud_Edit');
            $power['studNo'] = Power::exist('School_List_Stud_No');
            if ($power['studNo']) {
                $listButtonArr[] = ['id' => 'bt_list_set_studentNo', 'text' => '编辑序号', 'plain' => 'true', 'icon' => 'fa-pencil'];
            }
            $listButtonArr[] = ['id' => 'bt_list_import', 'class' => 'menubutton', 'text' => '导入', 'plain' => 'true', 'icon' => 'fa-file-excel-o'];
            $power['identity'] = Power::exist('School_List_Stud_Identity');
            $power['add'] = Power::exist('School_List_Stud_Add');
            $listButtonArr[] = ['id' => 'bt_list_more', 'class' => 'menubutton', 'text' => '更多', 'plain' => 'true', 'icon' => 'fa-info-circle'];
            if (Power::exist('Device_ReturnTab_Add')) {
                $listButtonArr[] = ['id' => 'bt_list_returnTab', 'text' => '退还申请', 'plain' => 'true', 'icon' => 'fa-tablet'];
            }

            if (Power::exist('School_List_Stud_UploadPayVou')) {
                $listButtonArr[] = ['id' => 'bt_list_payVoucher', 'text' => '缴费凭证', 'plain' => 'true', 'icon' => 'fa-file-image-o'];
            }
            if (Power::exist('LicenceDevList_Bind')) {
                $listButtonArr[] = ['id' => 'bt_list_bindLicence', 'text' => '绑定许可证', 'plain' => 'true', 'icon' => 'fa-link'];
            }
            if (Power::exist('Account_Use')) {
                $listButtonArr[] = ['id' => 'bt_account_use', 'class' => 'menubutton', 'text' => '账号用途', 'plain' => 'true', 'icon' => 'fa-ellipsis-v'];
            }
//            $power['uploadPayVoucher'] = Power::exist('School_List_Stud_UploadPayVou');
            $power['unbind'] = Power::exist('School_List_Stud_Device');
            $power['group'] = Power::exist('School_List_Group');
            $power['assist'] = Power::exist('School_List_Stud_Assist');
            $power['random'] = Power::exist('School_List_Stud_Random');
            $power['useType'] = Power::exist('Account_Use');
//            $power['configureList'] = Power::exist('School_List_User_Configure_List');
            $power['userSign'] = Power::exist('School_User_Sign');
        }
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_history', 'style' => 'width: 60px;', 'data' => [0 => '正常', 1 => '历史']];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_cost', 'style' => 'width: 65px;', 'data' => [0 => '-缴费-', 1 => '未缴', 2 => '已缴']];
        $nowYear = date('Y');
        $year = [];
        for ($i = 0; $i < 5; $i++) {
            $year[$nowYear - $i] = $nowYear - $i;
        }
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_cost_year', 'style' => 'width: 80px;', 'data' => $year, 'multiple' => 'true'];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_ebook', 'style' => 'width: 90px;', 'data' => ['' => '-电子书包-', 1 => '使用', 0 => '未使用'], 'default' => 1];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_dev', 'style' => 'width: 90px;', 'data' => ['' => '-购置方式-', 0 => '无', 1 => '购买', 2 => '租用', 3 => '借用']];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_payVoucher_status',
            'data' => [99 => '缴费凭证', 0 => '无'] + self::$payVoucherState, 'style' => 'width: 80px'];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_create_start', 'class' => 'easyui-datebox', 'style' => 'width: 100px;', 'label' => ' 创建： '];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_create_end', 'class' => 'easyui-datebox', 'style' => 'width: 100px;', 'label' => ' ~ '];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_items', 'multiple' => 'true', 'style' => 'width: 60px;', 'data' => [
            '' => '搜索', 'user.sAdClsName' => '班级', 'user.sUserName' => '姓名', 'user.sLogonName' => '账号'
        ]];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague', 'style' => 'width:150px;'];
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px'];
        if (Power::exist('School_List_Stud_Export')) {
            $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_export', 'text' => '导出', 'icon' => 'fa-file-excel-o', 'style' => 'margin-left:10px'];
        }
        return $this->view->setVars([
            'ClassList' => Template::createList('class_list', 'School_StudentClass'),
            'List' => Template::createList('list', 'School_Student', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'power' => $power
        ]);
    }


    /**
     * 学校教师管理页面（单学校管理）
     *
     * create by ck 20160706
     * modify by ck 20161008    js集合
     */
    public function teacherAction()
    {
        $this->view->setTemplateBefore('listForm');
        $this->view->pick('school/teacher');
//        $this->view->disableLevel(View::LEVEL_ACTION_VIEW);
        Main::showNavPosition('学校列表', ['学校设置', '教师管理'], true);
        Assets::importMainJs('assets/jquery/jquery.fileDownload.js');
        Assets::easyUI('js/school/teacher.js');
        $schoolId = $this->request->getQuery('iSchoolId', 'int');
        if (!School::hasPower($schoolId)) {
            return $this->sendViewError('无该学校查看权限');
        }
        if (!Power::exist('School_List_Tch')) {
            return $this->sendViewError('无教师管理权限！');
        }
        $listSearchArr = $listButtonArr = $formButtonArr = [];
        $managePower = School::hasPower($schoolId, true);
        $power = [
            'spare' => false,
            'auth' => false,
            'status' => false,
            'group' => false,
            'assist' => false,
            'random' => false,
        ];
        if ($managePower) {
            if (Power::exist('School_List_Tch_Login')) {
                $listButtonArr[] = ['id' => 'bt_list_login', 'text' => '扫码登陆', 'plain' => 'true', 'icon' => 'fa-tablet'];
            }
            if (Power::exist('School_List_Tch_Pwd')) {
                $listButtonArr[] = ['id' => 'bt_list_set_pwd', 'text' => '修改密码', 'plain' => 'true', 'icon' => 'fa-pencil'];
            }
            $listButtonArr[] = ['id' => 'bt_list_refresh_login', 'text' => '刷新登陆', 'plain' => 'true', 'icon' => 'fa-refresh'];

            $listButtonArr[] = ['id' => 'bt_list_tablet', 'class' => 'menubutton', 'text' => '机器使用', 'plain' => 'true', 'icon' => 'fa-pencil'];
            $listButtonArr[] = ['id' => 'bt_set', 'class' => 'menubutton', 'text' => '设置', 'plain' => 'true', 'icon' => 'fa-cog'];
            $listButtonArr[] = ['id' => 'bt_list_apply', 'class' => 'menubutton', 'text' => '申请', 'plain' => 'true', 'icon' => 'fa-pencil'];
            $power['spare'] = Power::exist('School_List_Spare');
            $power['userSign'] = Power::exist('School_User_Sign');
            if (Power::exist('School_List_Tch_Auth')) {
                $ips = Tool::getValue(Main::getConfigByName('admin'), 'companyIP', [], function ($ips) {
                    return explode(';', $ips);
                });
                if (empty($ips) || in_array(Tool::getIp(), $ips)) {
                    $power['auth'] = true;
                }
            }

//            if (Power::exist('School_List_Spare')){
//                $power['spare']  = true;
//                $listButtonArr[] = ['id' => 'bt_list_spare', 'class' => 'menubutton', 'text' => '备用机', 'plain' => 'true', 'icon' => 'fa-tablet'];
//            }
            if (Power::exist('Device_ReturnTab_Add')) {
                $listButtonArr[] = ['id' => 'bt_list_returnTab', 'text' => '退还申请', 'plain' => 'true', 'icon' => 'fa-tablet'];
            }
//            $listButtonArr[] = ['id' =>'bt_list_repair', 'text'=>'维修申请', 'plain'=>'true', 'icon'=>'fa-wrench'];
            if (Power::exist('School_List_Tch_Edit')) {
                $power['status'] = true;
                $listButtonArr[] = ['id' => 'bt_list_setName', 'text' => '修改姓名', 'plain' => 'true', 'icon' => 'fa-pencil'];
                $listButtonArr[] = ['id' => 'bt_list_status', 'class' => 'menubutton', 'text' => '更改状态', 'plain' => 'true', 'icon' => 'fa-history'];
                $listButtonArr[] = ['id' => 'bt_list_user_group', 'text' => '设置用户组', 'plain' => 'true', 'icon' => 'fa-pencil'];
//                $listButtonArr[] = ['id'=>'bt_list_set_history', 'text'=>'设为历史', 'plain'=>'true', 'icon'=>'fa-history'];
//                $listButtonArr[] = ['id'=>'bt_list_set_normal', 'text'=>'设为正常', 'plain'=>'true', 'icon'=>'fa-undo'];
            }
            $listButtonArr[] = ['id' => 'bt_list_more', 'class' => 'menubutton', 'text' => '更多', 'plain' => 'true', 'icon' => 'fa-info-circle'];
            if (Power::exist('School_List_Tch_Add')) {
                $listButtonArr[] = ['id' => 'bt_list_import', 'text' => '导入', 'plain' => 'true', 'icon' => 'fa-file-excel-o'];
            }
            if (Power::exist('School_List_Tch_Manage')) {
                $listButtonArr[] = ['id' => 'bt_list_manage', 'text' => '管理平台', 'plain' => 'true', 'icon' => 'fa-pencil'];
            }
            $power['useType'] = Power::exist('Account_Use');
            if ($power['useType']) {
                $listButtonArr[] = ['id' => 'bt_account_use', 'class' => 'menubutton', 'text' => '账号用途', 'plain' => 'true', 'icon' => 'fa-ellipsis-v'];
            }
            $power['group'] = Power::exist('School_List_Group');
            $power['assist'] = Power::exist('School_List_Tch_Assist');
            $power['random'] = Power::exist('School_List_Tch_Random');
        }
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_history', 'style' => 'width: 60px;', 'label' => '状态： ', 'data' => [0 => '正常', 1 => '历史']];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_items', 'multiple' => 'true', 'style' => 'width: 60px;', 'label' => ' 搜索： ', 'data' => [
            '' => '默认', 'user.sAdClsName' => '班级', 'user.sUserName' => '姓名', 'user.sLogonName' => '账号'
        ]];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague'];
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px'];
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_export', 'text' => '导出', 'icon' => 'fa-file-excel-o', 'style' => 'margin-left:10px'];
        return $this->view->setVars([
            'List' => Template::createList('list', 'School_Teacher', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'power' => $power
        ]);
    }


    /**
     * 其他用户列表
     *
     * @return View|string
     *
     * create by ck 20171211
     */
    public function otherUserAction()
    {
        $this->view->setTemplateBefore('listForm');
        Main::showNavPosition('学校列表', ['学校设置', '其他用户'], true);
        Assets::easyUI('js/school/otherUser.js');
        $schoolId = $this->request->getQuery('schoolId', 'int');
        if (!School::hasPower($schoolId)) {
            return $this->sendViewError('无该学校查看权限');
        }
        if (!Power::exist('School_List_OtherUser')) {
            return $this->sendViewError('无其他用户管理权限！');
        }
        $listSearchArr = $listButtonArr = $formButtonArr = [];
        $managePower = School::hasPower($schoolId, true);
        if ($managePower) {
            $listButtonArr[] = ['id' => 'bt_list_refresh_login', 'text' => '刷新登陆', 'plain' => 'true', 'icon' => 'fa-refresh'];
            if (Power::exist('School_List_OtherUser_Edit')) {
                $listButtonArr[] = ['id' => 'bt_list_set_history', 'text' => '设为历史', 'plain' => 'true', 'icon' => 'fa-history'];
                $listButtonArr[] = ['id' => 'bt_list_set_normal', 'text' => '设为正常', 'plain' => 'true', 'icon' => 'fa-undo'];
            }
        }
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_history', 'style' => 'width: 60px;', 'label' => '状态： ', 'data' => [0 => '正常', 1 => '历史']];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_items', 'multiple' => 'true', 'style' => 'width: 60px;', 'label' => ' 搜索： ', 'data' => [
            '' => '默认', 'sUserName' => '姓名', 'sLogonName' => '账号'
        ]];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague'];
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px'];
        return $this->view->setVars([
            'List' => Template::createList('list', 'School_OtherUser', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ])
        ]);
    }

    /**
     * 获取其他用户列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171211
     */
    public function getOtherUserAction()
    {
        $schoolId = $this->request->get('schoolId', 'int');
        $history = $this->request->get('history', 'int', 0);
        if (!$schoolId) {
            return $this->sendErrorResponse(400, '缺少学校ID');
        }
        try {
            $parameters = [
                'columns' => 'iUserId,sLogonName,sUserName,iUserSex,bCompany',
                'conditions' => 'bDelete = 0 AND bDisable = 0 AND iUserType NOT IN (1,4) AND bHistory = :history: AND iSchoolId = :schoolId: AND sLogonName <> "admin"',
                'bind' => ['history' => $history, 'schoolId' => $schoolId]
            ];

            //添加搜索条件
            Main::runSearchVagueConditions($parameters['conditions'], ['iUserId', 'sLogonName', 'sUserName']);
            $data = Main::runModelPage('\\Admin\\Models\\user\\XhsysUser', $parameters, $this->userEnum);

            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 根据学校id获取行政班列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171129
     * modify by sqb 20190108
     */
    public function getAdClassAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        if (!$schoolId) {
            return $this->sendErrorResponse(400, '学校id不能为空');
        }

        $data = XhsysUser::getClassInfoBySchoolId($schoolId);

        return $this->sendJsonResponse($data['classList']);
    }

    /**
     * 获取学校用户及绑定设备/应用信息
     *
     * @param bool|false $return
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|array|string
     *
     * create by ck 20170722
     * modify by ck 20170927    添加用户应用安装信息/备用机信息
     * modify by ck 20171129    可根据班级筛选
     * modify by ck 20171130    添加学号
     * modify by ck 20171205    可根据是否缴费筛选
     * modify by ck 20180206    添加购置方式及贫困等级
     * modify by ck 20180209    添加贫困生排序，购置方式筛选
     * modify by ck 20180313    添加教师子女属性
     * modify by ck 20180315    可根据用户id获取指定信息
     * modify by ck 20180412    教师无绑定设备或以学生端登陆过则显示红名
     * modify by ck 20180515    学生绑定时间与最后登陆时间一致或无登陆则显示红名
     * modify by ck 20180516    有绑定数据且未使用电子书包则更新字段（手动取消不更新）
     * modify by ck 20180523    筛选缴费支持多选年费
     * modify by zqk 2018129    缴费凭证
     */
    public function getUserAction($return = false)
    {
        $schoolId = $this->request->get('schoolId', 'int');
        $userType = $this->request->get('userType', 'int');
        $history = $this->request->get('history', 'int', 0);
        $classNames = $this->request->get('classNames', 'string');
        $cost = $this->request->get('cost', 'int', 0);
        $ebook = $this->request->get('ebook', 'int');
        $chargeYear = $this->request->get('chargeYear', 'int');
        $createStart = $this->request->get('createStart', 'string');
        $createEnd = $this->request->get('createEnd', 'string');
        $devSource = $this->request->get('devSource', 'int');
        $sort = $this->request->get('sort', 'string');
        $order = $this->request->get('order', 'string');
        $payStatus = $this->request->get('payStatus', 'int');
        $userIds = array_filter(explode(',', $this->request->get('userIds', 'string')));     //导出指定用户
        if (is_string($chargeYear)) {
            $chargeYear = array_filter(explode(',', $chargeYear));
        }
        if ($createEnd) {
            $createEnd = $createEnd . ' 23:59:59';
        }
        if (!$schoolId) {
            return $this->sendErrorResponse(400, '缺少学校ID');
        }
        if (!$userType) {
            return $this->sendErrorResponse(400, '缺少用户类型');
        }
        if (isset($payStatus) && in_array($payStatus, array_keys(self::$payVoucherState + [0 => '无']))) {
            $years = $chargeYear;
            if (empty($years)) {
                $years = [];
                $nowYear = date('Y');
                for ($i = 0; $i < 5; $i++) {
                    $years[] = $nowYear - $i;
                }
            }
            if ($years) {
                $build = $this->modelsManager->createBuilder()
                    ->columns('iUserId')
                    ->addFrom('Admin\Models\user\XhsysUserPayVoucher');
                if (is_array($years)) {
                    $build->where('bDelete = 0 and iChargeYear IN ({years:array})', ['years' => $years]);
                    $con = '';
                    foreach ($years as $k => $v) {
                        if ($payStatus == 1 or $payStatus == 3) {
                            if ($k == 0) {
                                $con .= " (iState = $payStatus And iChargeYear = $v)";
                            } else {
                                $con .= " or (iState = $payStatus And iChargeYear = $v)";
                            }
                            $build->andWhere($con);

                        } else if ($payStatus == 2) {
                            if ($k == 0) {
                                $con .= " (iState = $payStatus And iChargeYear = $v)";
                            } else {
                                $con .= " And (iState = $payStatus And iChargeYear = $v)";
                            }
                            $build->andWhere($con);
                        }
                    }
                } else {
                    $build->where("iChargeYear = $years");
                    if ($payStatus == 1) {
                        $build->andWhere('iState = 1');
                    } elseif ($payStatus == 2) {
                        $build->andWhere('iState = 2');
                    } elseif ($payStatus == 3) {
                        $build->andWhere('iState = 3');
                    }
                }
                $uids = $build->getQuery()->execute()->toArray();
                $uids = array_unique(array_column($uids, 'iUserId'));
            }
        }
        try {
            $builder = $this->modelsManager->createBuilder()
                ->columns(['user.iUserId', 'user.sUserName', 'user.sLogonName', 'user.sAdClsName', 'user.iUserSex', 'user.bEbook', 'user.iDevSource', 'user.iPoorLevel', 'user.tCreateDate', 'user.sIdentityCode', 'user.iType',
                    'device.iADLId', 'device.sDeviceNumber', 'device.sModel', 'device.sIP', 'device.sMac', 'device.sImei', 'device.tCreateDate as tDevCreateDate', 'device.sOsDisplay', 'device.sOsVersion', 'sd.iHistoryType'])
                ->from(['user' => '\\Admin\\Models\\user\\XhsysUser'])
                ->leftJoin('\\Admin\\Models\\device\\XhsysAccountdevicelocked', 'device.iUserId = user.iUserId AND IFNULL(device.bDelete, 0) = 0', 'device')
                ->leftJoin('\\Admin\\Models\\user\\XhsysUserstud', 'user.iUserId = sd.iUserId', 'sd')
//                ->leftJoin('\\Admin\\Models\\user\\XhsysUserPayVoucher', 'pay.iUserId = user.iUserId AND pay.bDelete = 0', 'pay')
                ->where('user.bDelete = 0 AND user.bDisable = 0')
//                ->where('user.bDelete = 0 AND user.bDisable = 0 AND user.bCompany = 0')
                ->andWhere('user.iUserType = :userType: AND user.iSchoolId = :schoolId: AND user.bHistory = :history: ', ['userType' => $userType, 'schoolId' => $schoolId, 'history' => $history])
                ->groupBy('user.iUserId');
            if ($userIds) {
                $builder->andWhere('user.iUserId IN ({userIds:array})', ['userIds' => $userIds]);
            }
            if ($userType == 1) {
                $builder->columns(array_merge($builder->getColumns(), ['stud.iTchChild', 'stud.iDevCost', 'stud.iSerCost', 'stud.iBehind']));
                $builder->leftJoin('\\Admin\\Models\\user\\XhsysUserstud', 'user.iUserId = stud.iUserId', 'stud');
            }
            if ($createStart) {
                $builder->andWhere('user.tCreateDate >= :createStart:', ['createStart' => $createStart]);
            }
            if ($createEnd) {
                $builder->andWhere('user.tCreateDate <= :createEnd:', ['createEnd' => $createEnd]);
            }
            //筛选是否缴费
            if ($cost) {
                $sql = "SELECT iStudId FROM \\Admin\\Models\\cost\\XhcostStudcharge AS cost WHERE cost.bDelete = 0 AND cost.iSumCost > 0";
                if ($chargeYear) {
                    $sql .= ' AND cost.iChargeYear IN (' . implode(',', $chargeYear) . ')';
                }
                if ($cost == 1) {
                    $builder->andWhere('user.iUserId NOT IN (' . $sql . ')');
                } else {
                    $builder->andWhere('user.iUserId IN (' . $sql . ')');
                }
            }
            if ($ebook !== null && $ebook !== '') {
                $builder->andWhere('user.bEbook = :ebook:', ['ebook' => $ebook]);
            }
            if ($classNames !== null) {
                $classNames = explode(',', $classNames);
                $builder->andWhere('user.sAdClsName IN ({classNames:array})', ['classNames' => $classNames]);
            }
            if ($devSource) {
                $builder->andWhere('user.iDevSource = :devSource:', ['devSource' => $devSource]);
            }
            if ($sort) {
                $builder->orderBy('user.' . $sort . ' ' . $order);
            }
            //添加搜索条件
            $conditions = '';
            Main::runSearchVagueConditions($conditions, ['user.iUserId', 'user.sLogonName', 'user.sUserName', 'user.sAdClsName', 'device.sDeviceNumber', 'device.sModel', 'device.sIP', 'device.sMac']);
            $conditions and $builder->andWhere($conditions);
            if (isset($uids)) {
                if ($payStatus == 0) {
                    $builder->notInWhere('user.iUserId', $uids);
                } else {
                    $builder->inWhere('user.iUserId', $uids);
                }
            }
            $data = Main::runBuilderPage($builder, $this->userEnum);

            if ($return) {
                return $data['rows'];
            }

            //替换用户名为小写
            foreach ($data['rows'] as $index => $row) {
                $userId = $data['rows'][$index]['iUserId'];
                $data['rows'][$index]['sLogonName'] = strtolower($row['sLogonName']);
                $condition = 'bDelete = 0 AND iUserId = ' . $userId;
                if ($chargeYear) {
                    $condition .= ' AND iChargeYear IN (' . implode(',', $chargeYear) . ')';
                }
                $paydata = XhsysUserPayVoucher::find([
                    'columns' => 'iState',
                    'conditions' => $condition,
                ])->toArray();
                if (empty($paydata)) {
                    $data['rows'][$index]['iStateName'] = '<span>无</span>';
                } else {
                    $states = array_column($paydata, 'iState');
                    if (in_array(1, $states)) {
                        $data['rows'][$index]['iStateName'] = '<span>' . self::$payVoucherState[1] . '</span>';
                    } elseif (in_array(3, $states)) {
                        $data['rows'][$index]['iStateName'] = '<span>' . self::$payVoucherState[3] . '</span>';
                    } else {
                        $data['rows'][$index]['iStateName'] = '<span>' . self::$payVoucherState[2] . '</span>';
                    }
                }

                $signData = Device::getSignInData([['userId' => $userId, 'deviceNumber' => $row['sDeviceNumber']]])[$userId];
                $data['rows'][$index]['iSignInStatus'] = $signData['signInStatus'] ? '开启' : '关闭';
                $data['rows'][$index]['iProtocolStatus'] = $signData['protocolStatus'] ? '开启' : '关闭';
                $data['rows'][$index]['iPartsStatus'] = $signData['partsStatus'] ? '开启' : '关闭';
                $data['rows'][$index]['iStatus'] = $signData['iStatus'] == 0 ? '未签收' : '已签收';
            }

            //绑定上报设备
            $rows = array_column($data['rows'], null, 'sLogonName');
            $accounts = array_keys($rows);
            if ($accounts) {
                $deviceInfo = XhsysUsertablet::find([
                    'columns' => 'iUTId,sNowReceiverAccount,iReceivePurpose,sDevNumber,sDevType,sMacAddress,tCreateDate',
                    'conditions' => 'bDelete = 0 AND bDone = 0 AND sNowReceiverAccount IN ({accounts:array})',
                    'bind' => ['accounts' => $accounts]
                ])->toArray();
                foreach ($deviceInfo as $info) {
                    $rows[strtolower($info['sNowReceiverAccount'])] = array_merge($rows[strtolower($info['sNowReceiverAccount'])], [
                        'iADLId' => '',
                        'iUTId' => $info['iUTId'],
                        'iReceivePurpose' => $info['iReceivePurpose'] ? '备用' : '自用',
                        'sDeviceNumber' => $info['sDevNumber'],
                        'sModel' => $info['sDevType'],
                        'sIP' => '',
                        'sMac' => $info['sMacAddress'],
                        'sImei' => '',
                        'sOsDisplay' => '',
                        'sOsVersion' => '',
                        'tCreateDate' => $info['tCreateDate'],
                    ]);
                }
                $data['rows'] = array_values($rows);
            }

            //绑定应用信息
            $httpClient = new HttpClient(Main::getConfigByName('jAppServer')['url']);
            $rows = array_column($data['rows'], null, 'iUserId');
            $users = [];
            foreach ($rows as $userId => $row) {
                if ($row['sDeviceNumber']) {
                    $users[] = ['userId' => intval($userId), 'deviceId' => $row['sDeviceNumber']];
                }
            }
            if ($users) {
                $response = $httpClient->postJson(sprintf('/api/v1/schools/%s/users/platform/app/installed?packageName=com.android.settings', $schoolId), ['users' => $users]);
                if ($response->isSuccess()) {
                    $appInfo = $response->toArray();
                    foreach ($appInfo as $info) {
                        $rows[$info['userId']] += [
//                            'platformPackage' => $info['platformPackage'],
                            'platformVersion' => $info['platformVersion'],
                            'installed' => $info['installed'] ? '是' : '否',
                            'appCode' => $info['appCode'],
                        ];
                    }
                    $data['rows'] = array_values($rows);
                }
            }

            //学生绑定收费信息，学号，借用设备，登陆情况
            if ($userType == 1) {
                $rows = array_column($data['rows'], null, 'iUserId');
                $userIds = array_keys($rows);
                if ($userIds) {
                    //绑定收费信息
                    $costInfo = XhcostStudcharge::find([
                        'columns' => 'iStudId AS studId,SUM(IFNULL(iSerCost, 0)) AS serCost,SUM(IFNULL(iDevCost, 0) + IFNULL(iDeposit, 0) + IFNULL(iRentCost, 0)) AS devCost, max(tExpireTime) as expireTime',
                        'conditions' => 'bDelete = 0 AND iSumCost > 0 AND (iDevCost > 0 OR iDeposit > 0 OR iRentCost > 0 OR iSerCost > 0) AND iStudId IN ({studIds:array})',
                        'bind' => ['studIds' => $userIds],
                        'group' => 'iStudId'
                    ])->toArray();
                    if ($costInfo) {
                        foreach ($costInfo as $info) {
                            $rows[$info['studId']]['devCost'] = $info['devCost'] ? '<i class="fa fa-check"></i>' : ($info['serCost'] ? '' : '未拆分');
                            $rows[$info['studId']]['expireTime'] = $info['expireTime'];
                        }
                    }

                    //绑定学号
                    $httpClient->setBaseUrl(Main::getConfigByName('user')['url']);
                    $response = $httpClient->get(sprintf('/api/v1/schools/%s/students/summary', $schoolId), ['studentIds' => implode(',', $userIds)]);
                    if ($response->isSuccess()) {
                        $body = $response->toArray();
                        foreach ($body as $info) {
                            $rows[$info['userId']]['studentNo'] = $info['studentNo'];
                        }
                    } else {
                        foreach ($rows as &$row) {
                            $row['studentNo'] = '获取失败';
                        }
                    }

                    //绑定借用
                    $borrowInfo = XhsysAccountdevicelocked::find([
                        'columns' => 'iUserId,iADLId,sDeviceNumber,sIP,sMac,sModel,sImei,tCreateDate',
                        'conditions' => "bDelete = 0 AND iSourceType = 2 AND iUserId IN ({studIds:array})",
                        'bind' => ['studIds' => $userIds]
                    ])->toArray();
                    if ($borrowInfo) {
                        foreach ($borrowInfo as $info) {
                            $rows[$info['iUserId']] = array_merge($rows[$info['iUserId']], $info);
                            $rows[$info['iUserId']]['iReceivePurpose'] = '借用';
                        }
                    }

                    //登陆次数及最后登陆时间
                    //modify by sqb 2018/12/13   优化加载界面加载时间 逻辑处理移至 getUserLoginInfo()
//                    $oldDB     = new Mysql(Main::getConfigByName('oldCenterDB'));
//                    $countInfo = $this->db->fetchAll('select lo_us_id as userId,count(*) as loginCount from login_log where  lo_us_id in (' . implode(',', $userIds) . ') group by lo_us_id ');

                    //有设备号则处理电子书包字段为“是”（包括备用/借用）
                    $devUserIds = [];
                    foreach ($rows as $userId => $row) {
                        if ($row['sDeviceNumber']) {
                            $devUserIds[] = $userId;
                        }
                    }
                    if ($devUserIds) {
                        $this->db->execute('update XHSys_User set bEbook = 1 where iUserId IN (:devUserIds) and bEbook = 0 and bEbookLock = 0', ['devUserIds' => implode(',', $devUserIds)]);
                    }

                    $data['rows'] = array_values($rows);
                }
                //设备归还
                $reTabArr = $this->getStuReTabletUserId($schoolId);
//                var_dump($reTabArr);die;
                if ($reTabArr) {
                    foreach ($data['rows'] as &$row) {
                        if (in_array($row['iUserId'], $reTabArr)) {
                            $row['reTabInfo'] = '<i class="fa fa-tablet fa-lg fa-fw" title="申请退还平板" style="color:grey;"></i>';
                        }
                    }
                }

                unset($row);
                //处理教师子女信息
                foreach ($data['rows'] as &$row) {
                    if ($row['iTchChild'] == $this->userEnum['iTchChild'][3]) {
                        $row['iTchChild'] = "<font color='#6699CC'>{$row['iTchChild']}</font>";
                        continue;
                    }
                    if ($row['iTchChild'] == $this->userEnum['iTchChild'][2]) {
                        $row['iTchChild'] = "<font color='#CC3333' title='设备费：{$row['iDevCost']}，服务费：{$row['iSerCost']}'>{$row['iTchChild']}</font>";
                    }
                }
                unset($row);
            }

            //教师查询设备是否有学生端登陆记录
//            if ($userType == 4) {
//                $oldDB           = new Mysql(Main::getConfigByName('oldCenterDB'));
//                $devNumberArr    = array_filter(array_column($data['rows'], 'sDeviceNumber'));
//                $devStudLoginArr = [];
//                if ($devNumberArr) {
//                    $devNumberStr    = implode("','",$devNumberArr);
//                    $devStudLogin    = $oldDB->fetchAll("select lo_computername from login_log where lo_user_agent = 'com.xuehai.launcher' and lo_computername in ('{$devNumberStr}')");
//                    $devStudLoginArr = array_column($devStudLogin,'lo_computername');
//                }
//
//                foreach ($data['rows'] as &$row) {
//                    if (!$row['sDeviceNumber']) {
//                        $row['sUserName'] = "<font color='red'>{$row['sUserName']}</font>";
//                        continue;
//                    }
//                    if (!$row['iReceivePurpose'] && array_search($row['sDeviceNumber'], $devStudLoginArr) !== false) {
//                        $row['sUserName'] = "<font color='red'>{$row['sUserName']}</font>";
//                        continue;
//                    }
//                }
//                unset($row);
//            }

            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $return ? $this->sendViewError($e->getMessage()) : $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 获取学生登录日志
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by sqb 2018/12/14
     */
    public function getUserLoginInfoAction()
    {
        $data = $this->request->get();

        if ($data['rows']) {
            $rows = array_column($data['rows'], null, 'iUserId');
            $userIds = array_keys($rows) ?: [];
            $loginInfo = $this->db->fetchAll('select t.lo_us_id as userId,t.lo_date as lastLoginDate,a.loginCount from login_log as t
                            left join ( select count(*) as loginCount,lo_us_id from  login_log group by lo_us_id ) as a on a.lo_us_id = t.lo_us_id 
                            where t.lo_id in ( select max(lo_id) as lo_id  from login_log  group by lo_us_id) and t.lo_us_id in (' . implode(',', $userIds) . ') ');
            $loginInfo = array_column($loginInfo, null, 'userId');
            foreach ($rows as $userId => &$row) {
                if (!isset($loginInfo[$userId])) {
                    $row['sUserName'] = "<font color='red'>{$row['sUserName']}</font>";
                    continue;
                }
                $row['loginCount'] = $loginInfo[$userId]['loginCount'];
                $row['lastLoginDate'] = $loginInfo[$userId]['lastLoginDate'];
                if ($row['tDevCreateDate'] && date('Y-m-d', strtotime($row['tDevCreateDate'])) == date('Y-m-d', strtotime($loginInfo[$userId]['lastLoginDate']))) {
                    $row['sUserName'] = "<font color='red'>{$row['sUserName']}</font>";
                }
            }
            foreach ($loginInfo as $login) {
                $userId = $login['userId'];
                $rows[$userId]['loginCount'] = $login['loginCount'];
                $rows[$userId]['lastLoginDate'] = $login['lastLoginDate'];
                if ($rows[$userId]['tDevCreateDate'] && date('Y-m-d', strtotime($rows[$userId]['tDevCreateDate'])) == date('Y-m-d', strtotime($login['lastLoginDate']))) {
                    $rows[$userId]['sUserName'] = "<font color='red'>{$rows[$userId]['sUserName']}</font>";
                }
            }

            return $this->sendJsonResponse(array_values($rows));
        } else {
            return $this->sendJsonResponse([]);
        }
    }

    /**
     * 获取归还设备学生userId
     *
     * @param $schoolId
     *
     * @return array
     *
     * create by dale  20180927
     */
    public function getStuReTabletUserId($schoolId)
    {
        $retTabArr = XHImsReturnTab::find([
            'conditions' => 'bDelete= 0 and mData like :key: and iState = 2 and iSource = 2',
            'bind' => ['key' => '%"' . $schoolId . '"%']
        ]);
        $arr = [];
        foreach ($retTabArr as $returnTab) {
            $data = $returnTab->mData;
            if (is_string($data)) {
                $data = $data ? unserialize($data) : [];
            }
            if ($data) {
                $userIdArr = array_column($data, 'iUserId');
                if ($userIdArr) {
                    $arr = array_merge($arr, $userIdArr);
                }
            }
        }
        $arr = array_values(array_filter(array_unique($arr)));
        return $arr;
    }

    /**
     * 设置电子书包
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171229
     * modify by ck 20180516    手动修改则锁定
     */
    public function setEbookStatusAction()
    {
        $ids = $this->request->getPost('ids', 'int');
        $used = $this->request->getPost('used', 'string') == 'true' ? 1 : 0;
        if (!Power::exist('School_List_Stud_Edit')) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        $result = $this->modelsManager->executeQuery("update \\Admin\\Models\\user\\XhsysUser set bEbook = :used:, bEbookLock = 1 where iUserType = 1 and iUserId in ({idArr:array})", ['used' => $used, 'idArr' => $ids]);
        if (!$result) {
            return $this->sendErrorResponse(500, '操作失败');
        }
        return $this->sendSuccessResponse('操作成功');
    }

    /**
     * 设置平板购置方式
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180206
     * modify by sqb 20190102
     */
    public function setDevSourceAction()
    {
        $ids = $this->request->getPost('ids', 'int');
        $source = $this->request->getPost('source', 'int');
        $comment = $this->request->getPost('comment', 'string');
        if (!Power::exist('School_List_Stud_Edit')) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        if (!in_array($source, array_keys($this->userEnum['iDevSource']))) {
            return $this->sendErrorResponse(400, '购置方式不正确');
        }

        foreach ($ids as $id) {
            $commentObj = XhsysUserComment::findFirst([
                'conditions' => "bDelete = 0 AND iType = 1 AND iUserId = :id:",
                'bind' => ['id' => $id]
            ]);

            $data = json_decode($commentObj->tComments, true);
            $data[$source] = $comment;

            if (!$commentObj) {//插入
                $commentObj = new XhsysUserComment();
                unset($data);
                $data = [1 => '', 2 => '', 3 => '', 4 => ''];
                $data[$source] = $comment;

                $commentObj->iUserId = $id;
            }
            $data = json_encode($data);

            $commentObj->tComments = $data;

            if (!$commentObj->save()) {
                return $this->sendErrorResponse(500, '操作失败');
            }
        }


        $result = $this->modelsManager->executeQuery("update \\Admin\\Models\\user\\XhsysUser set iDevSource = :source: where iUserType = 1 and iUserId in ({idArr:array})", ['source' => $source, 'idArr' => $ids]);
        if (!$result) {
            return $this->sendErrorResponse(500, '操作失败');
        }
        return $this->sendSuccessResponse('操作成功');
    }

    /**
     * 设置贫困生等级
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180206
     */
    public function setPoorLevelAction()
    {
        $ids = $this->request->getPost('ids', 'int');
        $level = $this->request->getPost('level', 'int');
        if (!Power::exist('School_List_Stud_Edit')) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        if (!in_array($level, array_keys($this->userEnum['iPoorLevel']))) {
            return $this->sendErrorResponse(400, '等级不正确');
        }
        $result = $this->modelsManager->executeQuery("update \\Admin\\Models\\user\\XhsysUser set iPoorLevel = :level: where iUserType = 1 and iUserId in ({idArr:array})", ['level' => $level, 'idArr' => $ids]);
        if (!$result) {
            return $this->sendErrorResponse(500, '操作失败');
        }
        return $this->sendSuccessResponse('操作成功');
    }

    /**
     * 设置学生教师子女属性
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180313
     */
    public function setTchChildAction()
    {
        $ids = $this->request->getPost('ids', 'int');
        $level = $this->request->getPost('level', 'int');
        $devCost = $this->request->getPost('devCost', 'int', 0);
        $serCost = $this->request->getPost('serCost', 'int', 0);
        if (!Power::exist('School_List_Stud_Edit')) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        if (!in_array($level, array_keys($this->userEnum['iTchChild']))) {
            return $this->sendErrorResponse(400, '等级不正确');
        }
        if ($level == 2 && !$devCost && !$serCost) {
            $level = 3;
        }
        try {
            $this->db->begin();
            foreach ($ids as $id) {
                $studInfo = XhsysUserstud::findFirst($id);
                if (!$studInfo) {
                    $studInfo = new XhsysUserstud([
                        'iUserId' => $id
                    ]);
                }
                $studInfo->iTchChild = $level;
                $studInfo->iDevCost = $devCost;
                $studInfo->iSerCost = $serCost;
                if (!$studInfo->save()) {
                    throw new \Exception($studInfo->getMessages()[0]);
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('操作成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $e->getMessage());
        }
//        $result = $this->modelsManager->executeQuery("update \\Admin\\Models\\user\\XhsysUser set iPoorLevel = :level: where iUserType = 1 and iUserId in ({idArr:array})", ['level' => $level, 'idArr' => $ids]);
//        if (!$result) {
//            return $this->sendErrorResponse(500, '操作失败');
//        }
//        return $this->sendSuccessResponse('操作成功');
    }

    /**
     * 设置是否留守儿童
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180807
     */
    public function setStudBehindAction()
    {
        $ids = $this->request->getPost('ids', 'int');
        $behind = $this->request->getPost('behind', 'int');
        if (!Power::exist('School_List_Stud_Edit')) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        if (!$ids) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        if (!in_array($behind, array_keys($this->userEnum['iBehind']))) {
            return $this->sendErrorResponse(400, '参数不正确');
        }
        try {
            $this->db->begin();
            foreach ($ids as $id) {
                $studInfo = XhsysUserstud::findFirst($id);
                if (!$studInfo) {
                    $studInfo = new XhsysUserstud([
                        'iUserId' => $id
                    ]);
                }
                $studInfo->iBehind = $behind;
                if (!$studInfo->save()) {
                    throw new \Exception($studInfo->getMessages()[0]);
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('操作成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, '操作失败', $e->getMessage());
        }
    }

    /**
     * 导出学生信息
     *
     * create by ck 20171201
     * modify by ck 20180125    添加IMEI号
     * modify by ck 20180827    重构
     */
    public function exportUserTabletAction()
    {
        $this->view->disable();
        error_reporting(E_ERROR);
        try {
            $data = $this->getUserAction(true);
            $isTch = $this->request->get('userType', 'int') == 4;

            $objPHPExcel = new Spreadsheet();
            $objPHPExcel->setActiveSheetIndex(0);
            $sheet = $objPHPExcel->getActiveSheet();
            $sheet->setTitle('平板领用签收表');

            //所有单元格居中
            $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
            $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(Alignment::VERTICAL_CENTER);
            $objPHPExcel->getDefaultStyle()->getFont()->setSize(12)->setName('宋体');

            //设置头
            $sheet->getRowDimension(1)->setRowHeight(40);
            $sheet->mergeCells('A1:J1');
            $sheet->setCellValue('A1', '学海智通云教育平台软件V2.0（含三星平板）签收表');
            $sheet->getStyleByColumnAndRow('A', 1)->getFont()->setSize(18);

            $sheet->getRowDimension(2)->setRowHeight(28);
            $sheet->mergeCells('A2:B2');
            $sheet->setCellValue('A2', '学校：');
            $sheet->getStyleByColumnAndRow('A', 2)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);
            $sheet->mergeCells('F2:G2');
            $sheet->setCellValue('F2', '类别：');
            $sheet->getStyleByColumnAndRow('F', 2)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_LEFT);

            //插入图片
            $objDrawing = new Drawing();
            $objDrawing->setName('logo');
            $objDrawing->setPath('frontend/img/xh_logo.png');
            $objDrawing->setHeight(36);
            $objDrawing->setCoordinates('A1');//图片名称所在的单元格
            $objDrawing->setOffsetX(10);
            $objDrawing->setOffsetY(10);
            $objDrawing->setWorksheet($sheet);


            $titleArr = [
                ['name' => '序号', 'width' => '5'],
                ['name' => '班级', 'width' => '6'],
                ['name' => '姓名', 'width' => '10'],
                ['name' => '账号', 'width' => '20'],
                ['name' => '设备号', 'width' => '20'],
                ['name' => 'IMEI', 'width' => '18'],
                ['name' => '状态', 'width' => '6'],
                ['name' => $isTch ? '签名' : '学生签名', 'width' => '10'],
                ['name' => '签收时间', 'width' => '10'],
                ['name' => $isTch ? '手机号' : '家长手机', 'width' => '15']
            ];

            //设置excel列名
            $cell = 'A';
            $bCell = '';
            $sheet->getRowDimension(3)->setRowHeight(30);
            foreach ($titleArr as $key => $title) {
                if ($cell > 'Z') {
                    if ($bCell == '') {
                        $bCell = 'A';
                    } else {
                        $bCell++;
                    }
                    $cell = 'A';
                }
                $sheet->setCellValue($bCell . $cell . '3', $title['name']);
                $sheet->getColumnDimension($bCell . $cell)->setWidth($title['width']);
                $cell++;
            }

            //把数据循环写入excel中
            foreach ($data as $key => $row) {
                $key += 4;
                $sheet->setCellValueExplicit('A' . $key, $key - 3, DataType::TYPE_STRING);
                $sheet->setCellValueExplicit('B' . $key, $isTch ? '' : $row['sAdClsName'], DataType::TYPE_STRING);
                $sheet->setCellValueExplicit('C' . $key, $row['sUserName'], DataType::TYPE_STRING);
                $sheet->setCellValueExplicit('D' . $key, $row['sLogonName'], DataType::TYPE_STRING);
                $sheet->setCellValueExplicit('E' . $key, $row['sDeviceNumber'], DataType::TYPE_STRING);
                $sheet->setCellValueExplicit('F' . $key, $row['sImei'], DataType::TYPE_STRING);
                $sheet->setCellValueExplicit('G' . $key, '合格', DataType::TYPE_STRING);

                $sheet->getRowDimension($key)->setRowHeight(30);
            }

            //边框线
            $sheet->getStyle('A3:J' . (count($data) + 3))->applyFromArray([
                'borders' => [
                    'allBorders' => [
                        //'style' => PHPExcel_Style_Border::BORDER_THICK,   //边框是粗的
                        'borderStyle' => Border::BORDER_THIN,     //细边框
                        //'color' => array('argb' => 'FFFF0000'),
                    ],
                ]
            ]);

            //导出代码
//            $objWriter = IOFactory::createWriter($objPHPExcel, 'Xlsx');
            $objWriter = new Xlsx($objPHPExcel);
            $fileName = XhschoolInfo::getSchoolSupportArray()[$this->request->get('schoolId', 'int')] . '-签收表.xlsx';
//            header('Content-Type: application/vnd.ms-excel');
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . $fileName . '"');
            header('Cache-Control: max-age=0');
            $objWriter->save('php://output');
            return true;
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }

//        $this->view->disable();
//        try {
//            $data  = $this->getUserAction(true);
//            $isTch = $this->request->get('userType', 'int') == 4;
//
//            require_once APP_PATH . '/common/library/PHPExcel/PHPExcel.php';
//            require_once APP_PATH . '/common/library/PHPExcel/PHPExcel/IOFactory.php';
//
//            $objPHPExcel = new \PHPExcel();
//            $objPHPExcel->setActiveSheetIndex(0);
//            $sheet = $objPHPExcel->getActiveSheet();
//            $sheet->setTitle('平板领用签收表');
//
//            //所有单元格居中
//            $objPHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
//            $objPHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
//            $objPHPExcel->getDefaultStyle()->getFont()->setSize(12)->setName('宋体');
//
//            //设置头
//            $sheet->getRowDimension(1)->setRowHeight(40);
//            $sheet->mergeCells('A1:J1');
//            $sheet->setCellValue('A1', '学海智通云教育平台软件V2.0（含三星平板）签收表');
//            $sheet->getStyleByColumnAndRow('A', 1)->getFont()->setSize(18);
//
//            $sheet->getRowDimension(2)->setRowHeight(28);
//            $sheet->mergeCells('A2:B2');
//            $sheet->setCellValue('A2', '学校：');
//            $sheet->getStyleByColumnAndRow('A', 2)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
//            $sheet->mergeCells('F2:G2');
//            $sheet->setCellValue('F2', '类别：');
//            $sheet->getStyleByColumnAndRow('F', 2)->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
//
//            //插入图片
//            $objDrawing = new \PHPExcel_Worksheet_Drawing();
//            $objDrawing->setName('logo');
//            $objDrawing->setPath('frontend/img/xh_logo.png');
//            $objDrawing->setHeight(36);
//            $objDrawing->setCoordinates('A1');//图片名称所在的单元格
//            $objDrawing->setOffsetX(10);
//            $objDrawing->setOffsetY(10);
//            $objDrawing->setWorksheet($sheet);
//
//
//            $titleArr = [
//                ['name' => '序号', 'width' => '5'],
//                ['name' => '班级', 'width' => '6'],
//                ['name' => '姓名', 'width' => '10'],
//                ['name' => '账号', 'width' => '20'],
//                ['name' => '设备号', 'width' => '20'],
//                ['name' => 'IMEI', 'width' => '18'],
//                ['name' => '状态', 'width' => '6'],
//                ['name' => $isTch ? '签名' : '学生签名', 'width' => '10'],
//                ['name' => '签收时间', 'width' => '10'],
//                ['name' => $isTch ? '手机号' : '家长手机', 'width' => '15']
//            ];
//
//            //设置excel列名
//            $cell = 'A';
//            $bCell = '';
//            $sheet->getRowDimension(3)->setRowHeight(30);
//            foreach ($titleArr as $key => $title) {
//                if ($cell > 'Z') {
//                    if ($bCell == '') {
//                        $bCell = 'A';
//                    } else {
//                        $bCell++;
//                    }
//                    $cell = 'A';
//                }
//                $sheet->setCellValue($bCell . $cell . '3', $title['name']);
//                $sheet->getColumnDimension($bCell . $cell)->setWidth($title['width']);
//                $cell++;
//            }
//
//            //把数据循环写入excel中
//            foreach($data as $key => $row){
//                $key += 4;
//                $sheet->setCellValueExplicit('A' . $key, $key - 3);
//                $sheet->setCellValueExplicit('B' . $key, $isTch ? '' : $row['sAdClsName']);
//                $sheet->setCellValueExplicit('C' . $key, $row['sUserName']);
//                $sheet->setCellValueExplicit('D' . $key, $row['sLogonName']);
//                $sheet->setCellValueExplicit('E' . $key, $row['sDeviceNumber']);
//                $sheet->setCellValueExplicit('F' . $key, $row['sImei']);
//                $sheet->setCellValueExplicit('G' . $key, '合格');
//                $sheet->getRowDimension($key)->setRowHeight(30);
//            }
//
//            //边框线
//            $sheet->getStyle('A3:J'. (count($data) + 3))->applyFromArray([
//                'borders' => [
//                    'allborders' => [
//                        //'style' => PHPExcel_Style_Border::BORDER_THICK,   //边框是粗的
//                        'style' => \PHPExcel_Style_Border::BORDER_THIN,     //细边框
//                        //'color' => array('argb' => 'FFFF0000'),
//                    ],
//                ]
//            ]);
//
//            //导出代码
//            $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
//            $fileName  = XhschoolInfo::getSchoolSupportArray()[$this->request->get('schoolId', 'int')] . '-签收表.xlsx';
//            header('Content-Type: application/vnd.ms-excel');
//            header('Content-Type: application/octet-stream');
//            header('Content-Disposition: attachment; filename="' . $fileName . '"');
//            header('Cache-Control: max-age=0');
//            return $objWriter->save('php://output');
//        }
//        catch (\Exception $e) {
//            return $this->sendViewError($e->getMessage());
//        }
    }

    /**
     * 导出用户平板MAC地址
     *
     * @return bool|string
     *
     * create by ck 20180402
     */
    public function exportUserTabletMacAction()
    {
        $this->view->disable();
        try {
            $data = $this->getUserAction(true);

            $title = ['姓名', '账号', '设备号', 'Mac'];
            foreach ($data as &$row) {
                $row = [
                    'sUserName' => $row['sUserName'],
                    'sLogonName' => $row['sLogonName'],
                    'sDeviceNumber' => $row['sDeviceNumber'],
                    'sMac' => $row['sMac'],
                ];
            }

            $fileName = XhschoolInfo::getSchoolSupportArray()[$this->request->get('schoolId', 'int')] . '-mac';
            Tool::exportExcelOnline($fileName, $title, $data, 'xlsx', ['autoWidth' => true]);
            return true;
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 更改学生学号
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171203
     */
    public function updateStudentNoAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        $info = $this->request->getPost('info');
        if (!$schoolId || !$info) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        $httpClient = new HttpClient(Main::getConfigByName('user')['url']);
        $response = $httpClient->patchJson(sprintf('/api/v1/schools/%s/students/number', $schoolId), $info);
        if (!$response->isSuccess()) {
            return $this->sendErrorResponse(500, '修改失败', $response);
        }
        return $this->sendSuccessResponse('修改成功');
    }

    /**
     * 导入学生
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180507
     * modify by ck 20180719    自动创建班级
     * modify by ck 20180905
     */
    public function importStudentAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        $autoClass = $this->request->getPost('autoClass', 'int');
        $type = $this->request->getPost('type', 'int');
        $file = $this->request->getUploadedFiles()[0];
        if (!$schoolId || !$file) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }

        //检查权限
        if (!Power::exist('School_List_Stud_Add')) {
            return $this->sendErrorResponse(400, '无导入权限');
        }
        if (!School::hasPower($schoolId, true)) {
            return $this->sendErrorResponse(400, '没有该学校管理权限');
        }
        if (!School::isApproval($schoolId)) {
            return $this->sendErrorResponse(400, '该学校未审核，无法导入');
        }

        //读取数据并写入数据库
        try {
            $result = Tool::readExcel($file->getTempName(), true, pathinfo($file->getName())['extension']);
            $titleArr = $result['title'];
            $rows = $result['data'];
            $pwd = strtoupper(md5(Tool::getValue(Main::getConfigByName('admin'), 'defaultPwd', '123456')));

            //检查必要参数是否存在，并替换其index值
            $mainIndex = ['sUserName' => '姓名', 'sLogonName' => '登录名'];
            foreach ($mainIndex as $key => $name) {
                $index = array_search($name, $titleArr);
                if ($index === false) {
                    return $this->sendErrorResponse(400, "缺少[{$name}]项信息");
                }
                $mainIndex[$key] = $index;
            }

            $extraIndex = [
                'sIdentityCode' => '身份证号',
                'sAdClsName' => '班级',
                'iUserSex' => '性别',
                'sBirthday' => '出生日期',
                'sFatherPhone' => '父亲手机',
                'sMotherPhone' => '母亲手机',
                'sOtherPhone' => '其他手机',
                'pClass' => '培优班'
            ];
            foreach ($extraIndex as $key => $name) {
                $extraIndex[$key] = array_search($name, $titleArr);
            }
            $extraIndex = array_filter($extraIndex);
            $fieldIndex = array_merge($mainIndex, $extraIndex);

            //检查登陆名是否重复
            $logonNames = array_filter(array_column($rows, $fieldIndex['sLogonName']));
            if (!$logonNames) {
                throw new \Exception('数据不能为空');
            }
            $checkUser = XhsysUser::count([
                'conditions' => 'bDelete = 0 AND sLogonName IN ({logonNames:array})',
                'bind' => ['logonNames' => $logonNames]
            ]);
            if ($checkUser) {
                throw new \Exception('学生用户名重复');
            }

            //插入数据库
            $classInfo = [];
            foreach ($rows as $row) {
                if (!$row[$fieldIndex['sLogonName']]) {
                    continue;
                }
                $user = new XhsysUser([
                    'sLogonPwd' => $pwd,
                    'iSchoolId' => $schoolId,
                    'iUserType' => 1,
                    'iType' => $type
                ]);
                foreach ($fieldIndex as $key => $index) {
                    switch ($key) {
                        case 'iUserSex':
                            $user->$key = $row[$index] == '男' ? 1 : ($row[$index] == '女' ? 2 : 0);
                            break;
                        case 'sBirthday':
                            $user->$key = date('Y-m-d', strtotime($row[$index]));
                            break;
                        case 'pClass':
                            break;
                        default:
                            $user->$key = $row[$index];
                    }
                }
                if (!$user->save()) {
                    throw new \Exception("{$fieldIndex['sUserName']}:{$fieldIndex['sLogonName']}，新建失败");
                }

                switch ($autoClass) {
                    case 1:
                        if (isset($fieldIndex['sAdClsName']) && $row[$fieldIndex['sAdClsName']]) {
                            $classInfo[$row[$fieldIndex['sAdClsName']]][] = $user->iUserId;
                        }
                        break;
                    case 2:
                        if (isset($fieldIndex['pClass']) && $row[$fieldIndex['pClass']]) {
                            $classInfo[$row[$fieldIndex['pClass']]][] = $user->iUserId;;
                        }
                        break;
                }
            }
            if ($classInfo) {
                UserService::initStudClass($schoolId, $classInfo, $autoClass - 1);
            }
            return $this->sendSuccessResponse('导入成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 导入教师账号
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180702
     * modify by ck 20180718    增加属性，自动加入班级
     * modify by ck 20181025    自动加入教师组
     */
    public function importTeacherAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        $type = $this->request->getPost('type', 'int');
        $file = $this->request->getUploadedFiles()[0];
        if (!$schoolId || !$file) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }

        //检查权限
        if (!Power::exist('School_List_Tch_Add')) {
            return $this->sendErrorResponse(400, '无导入权限');
        }
        if (!School::hasPower($schoolId, true)) {
            return $this->sendErrorResponse(400, '没有该学校管理权限');
        }
        if (!School::isApproval($schoolId)) {
            return $this->sendErrorResponse(400, '该学校未审核，无法导入');
        }

        //读取数据并写入数据库
        try {
            $result = Tool::readExcel($file->getTempName(), true, pathinfo($file->getName())['extension']);
            $titleArr = $result['title'];
            $rows = $result['data'];
            $pwd = strtoupper(md5(Tool::getValue(Main::getConfigByName('admin'), 'defaultPwd', '123456')));

            //检查必要参数是否存在，并替换其index值
            $mainIndex = ['sUserName' => '姓名', 'sLogonName' => '登录名'];
            foreach ($mainIndex as $key => $name) {
                $index = array_search($name, $titleArr);
                if ($index === false) {
                    return $this->sendErrorResponse(400, "缺少[{$name}]项信息");
                }
                $mainIndex[$key] = $index;
            }

            //获取枚举列表
            $enum = [
                'iUserSex' => [1 => '男', 2 => '女'],
                'iCurGrade' => XhsysEnum::getEnumByNodeName('年级'),
                'iSubject' => XhsysEnum::getEnumByNodeName('学科'),
//                'resSubject' => ResBase::getDictionaries('subject')
            ];
            $tchClass = [];

            $extraIndex = [
                'sSelfPhone' => '手机号',
                'iUserSex' => '性别',
                'iCurGrade' => '年级',
                'iSubject' => '学科',
                'sAdminClass' => '班级',
                'sLogonPwd' => '密码'
            ];
            foreach ($extraIndex as $key => $name) {
                $extraIndex[$key] = array_search($name, $titleArr);
            }
            $extraIndex = array_filter($extraIndex);
            $fieldIndex = array_merge($mainIndex, $extraIndex);

            //检查登陆名是否重复
            $logonNames = array_filter(array_column($rows, $fieldIndex['sLogonName']));
            if (!$logonNames) {
                throw new \Exception('数据不能为空');
            }
            $checkUser = XhsysUser::count([
                'conditions' => 'bDelete = 0 AND sLogonName IN ({logonNames:array})',
                'bind' => ['logonNames' => $logonNames]
            ]);
            if ($checkUser) {
                throw new \Exception("用户名包含{$checkUser}个重复");
            }

            //获取教师组id
            $groupName = ['老师组', '题池组卷', '视频音频'];
            $groupIds = XhsysGroup::find([
                'columns' => 'iGroupId',
                'conditions' => 'iType = 3 AND sName IN ({groupName:array})',
                'bind' => ['groupName' => $groupName]
            ])->toArray();
            $groupIds = array_column($groupIds, 'iGroupId');

            //插入数据库
            foreach ($rows as $row) {
                if (!$row[$fieldIndex['sLogonName']]) {
                    continue;
                }
                $user = new XhsysUser([
                    'sLogonPwd' => $pwd,
                    'iSchoolId' => $schoolId,
                    'iUserType' => 4,
                    'iType' => $type
                ]);
                $userTch = new XhsysUserTch();
                foreach ($fieldIndex as $key => $index) {
                    switch ($key) {
                        case 'sUserName':
                        case 'sLogonName':
                        case 'sSelfPhone':
                            $user->$key = $row[$index];
                            break;
                        case 'sLogonPwd':
                            $user->$key = $row[$index] ? strtoupper(md5($row[$index])) : $pwd;
                            break;
                        case 'iUserSex':
                            $user->$key = array_search($row[$index], $enum[$key]) ?: 0;
                            break;
                        case 'iSubject':
                        case 'iCurGrade':
                            $userTch->$key = array_search($row[$index], $enum[$key]) ?: 0;
                            break;
                        case 'sAdminClass':
                            $userTch->$key = $row[$index];
                            break;
                    }

                }
                if (!$user->save()) {
                    throw new \Exception("{$fieldIndex['sUserName']}:{$fieldIndex['sLogonName']}，新建失败");
                }
                $userTch->iUserId = $user->iUserId;
                $userTch->save();

                //处理行政班
                if ($userTch->sAdminClass && $userTch->iSubject) {
                    $tchClass[] = [
                        'tchId' => $user->iUserId,
                        'subject' => Tool::getValue($enum['iSubject'], $userTch->iSubject, ''),
                        'classNames' => explode(',', $userTch->sAdminClass)
                    ];
                }

                //加入教师组
                if ($groupIds) {
                    foreach ($groupIds as $groupId) {
                        (new XhsysGroupuser(['iGroupId' => $groupId, 'iUserId' => $user->iUserId]))->save();
                    }
                }
            }
            UserService::initTchClass($schoolId, $tchClass);
            return $this->sendSuccessResponse('导入成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 导入学生身份证
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180227
     */
    public function importStudIdentityAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        $file = $this->request->getUploadedFiles()[0];
        if (!$schoolId || !$file) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }
        $fileName = $file->getName();

        if (Tool::isWindows()) {
            $fileName = iconv('utf-8', 'GBK', $fileName);
        }
        $filePath = Tool::buildPath(TEMP_PATH, $fileName);
        $file->moveTo($filePath);

        //读取数据并写入数据库
        $this->db->begin();
        $importNum = $totalNum = 0;
        $errorUser = [];
        try {
            $result = Tool::readExcel($filePath, true);
            $titleArr = $result['title'];
            $rows = $result['data'];
            @unlink($filePath);

            //检查必要参数是否存在，并替换其index值
            $mainIndex = ['userName' => '姓名', 'logonName' => '登录名', 'code' => '身份证'];
            foreach ($mainIndex as $key => $name) {
                $index = array_search($name, $titleArr);
                if ($index === false) {
                    return $this->sendErrorResponse(400, "缺少[{$name}]项信息");
                }
                $mainIndex[$key] = $index;
            }

            foreach ($rows as $row) {
                //缺少参数则跳过
                if (!$row[$mainIndex['logonName']]) {
                    continue;
                }
                $totalNum++;

                //判断是否有身份证
                if (!$row[$mainIndex['code']]) {
                    $errorUser[] = ['userName' => $row[$mainIndex['userName']], 'logonName' => $row[$mainIndex['logonName']], 'reason' => '身份证号不能为空'];
                    continue;
                }

                //获取学生
                $user = XhsysUser::findFirst([
                    'conditions' => 'sLogonName = :logonName: AND iSchoolId = :schoolId: AND bDelete = 0',
                    'bind' => ['logonName' => $row[$mainIndex['logonName']], 'schoolId' => $schoolId]
                ]);
                if (!$user) {
                    $errorUser[] = ['userName' => $row[$mainIndex['userName']], 'logonName' => $row[$mainIndex['logonName']], 'reason' => '找不到该用户'];
                    continue;
                }
                $user->sIdentityCode = $row[$mainIndex['code']];

                if (!$user->save()) {
                    $errorUser[] = ['userName' => $row[$mainIndex['userName']], 'logonName' => $row[$mainIndex['logonName']], 'reason' => '保存失败'];
                    continue;
                }
                $importNum++;
            }
            $this->db->commit();
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
        $msg = "成功导入{$importNum}条！（共{$totalNum}条）";
        return $this->sendJsonResponse([
            'msg' => $msg,
            'errorData' => $errorUser,
        ], true);
    }

    /**
     * 导入学生序号
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180310
     */
    public function importStudNoAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        $file = $this->request->getUploadedFiles()[0];
        if (!$schoolId || !$file) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }
        $fileName = $file->getName();

        if (Tool::isWindows()) {
            $fileName = iconv('utf-8', 'GBK', $fileName);
        }
        $filePath = Tool::buildPath(TEMP_PATH, $fileName);
        $file->moveTo($filePath);

        //读取数据并写入数据库
        $errorUser = [];
        try {
            $result = Tool::readExcel($filePath, true);
            $titleArr = $result['title'];
            $rows = $result['data'];
            @unlink($filePath);

            //检查必要参数是否存在，并替换其index值
            $mainIndex = ['userName' => '姓名', 'logonName' => '登录名', 'studNo' => '序号'];
            foreach ($mainIndex as $key => $name) {
                $index = array_search($name, $titleArr);
                if ($index === false) {
                    throw new \Exception("缺少[{$name}]项信息");
                }
                $mainIndex[$key] = $index;
            }

            $logonNameArr = array_column($rows, $mainIndex['logonName']);
            $totalNum = count($logonNameArr);

            $userInfo = XhsysUser::find([
                'columns' => 'iUserId,sLogonName',
                'conditions' => 'bDelete = 0 AND iSchoolId = :schoolId: AND sLogonName IN ({logonName:array})',
                'bind' => ['schoolId' => $schoolId, 'logonName' => $logonNameArr]
            ])->toArray();
            if (!$userInfo) {
                throw new \Exception('找不到用户信息');
            }
            $userIds = array_column($userInfo, 'iUserId', 'sLogonName');
            $importNum = count($userInfo);

            //组合数据
            $info = [];
            foreach ($rows as $row) {
                if (!$row[$mainIndex['studNo']]) {
                    $errorUser[] = ['userName' => $row[$mainIndex['userName']], 'logonName' => $row[$mainIndex['logonName']], 'reason' => '序号不能为空'];
                    continue;
                }
                if (!isset($userIds[$row[$mainIndex['logonName']]])) {
                    $errorUser[] = ['userName' => $row[$mainIndex['userName']], 'logonName' => $row[$mainIndex['logonName']], 'reason' => '用户不存在'];
                    continue;
                }
                $userId = intval($userIds[$row[$mainIndex['logonName']]]);
                $info[] = ['studentId' => $userId, 'studentNo' => $row[$mainIndex['studNo']]];
            }

            $httpClient = new HttpClient(Main::getConfigByName('user')['url']);
            $response = $httpClient->patchJson(sprintf('/api/v1/schools/%s/students/number', $schoolId), $info);
            if (!$response->isSuccess()) {
                return $this->sendErrorResponse(500, '修改失败', $response);
            }
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
        $msg = "成功导入{$importNum}条！（共{$totalNum}条）";
        return $this->sendJsonResponse([
            'msg' => $msg,
            'errorData' => $errorUser,
        ], true);
    }

    /**
     * 获取登陆二维码
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180529
     */
    public function getLoginQRAction()
    {
        $userId = $this->request->getPost('userId', 'int');
        if (!$userId) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        $data = [
            'account' => User::getLogonName($userId),
            'password' => Main::getSecretKey(),
            'currentId' => intval(User::getId())
        ];
        return $this->sendSuccessResponse(Tool::getQRBase64Uri(json_encode($data)));
    }

    /**
     * 生成学生设备认证码
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180411
     * modify by ck 20180423    添加当前用户id
     * modify by ck 20180514    添加公司ip判断
     */
//    public function studAuthQRAction()
//    {
//        $userId = $this->request->getPost('userId', 'int');
//        if (!$userId) {
//            return $this->sendErrorResponse(400, '缺少学生id');
//        }
//        try {
//            $ips = Tool::getValue(Main::getConfigByName('admin'), 'companyIP', [], function ($ips) {
//                return explode(';', $ips);
//            });
//            if ($ips && !in_array(Tool::getIp(), $ips)) {
//                throw new \Exception('请在公司内操作');
//            }
//
//            $info = XhsysUserstud::findFirst($userId);
//            if (!$info) {
//                $info = new XhsysUserstud(['iUserId' => $userId]);
//                if (!$info->save()) {
//                    throw new \Exception($info->getError());
//                }
//                $info = XhsysUserstud::findFirst($userId);
//            }
//            if (!$info->bAuthUseful) {
//                throw new \Exception('不可操作');
//            }
//            $config = Main::getConfigByName('admin');
//            $pwd    = array_key_exists('defaultPwd', $config) && $config['defaultPwd'] ? $config['defaultPwd'] : '123456';
//            if (!$info->sAuthCode) {
//                $info->sAuthCode = substr(md5($userId . date('mYd'). $pwd), 0, 30);
//                if (!$info->save()) {
//                    throw new \Exception($info->getError());
//                }
//            }
//            $auth = [
//                'account'   => User::getLogonName($userId),
//                'password'  => $pwd,
//                'code'      => $info->sAuthCode,
//                'currentId' => intval(User::getId())
//            ];
//            ob_start();
//            QRcode::png(json_encode($auth),false, 0, 10, 1);
//            $imgString = base64_encode(ob_get_contents());
//            ob_end_clean();
//            return $this->sendSuccessResponse($imgString, false);
//        }
//        catch (\Exception $e) {
//            return $this->sendErrorResponse(500, $e->getMessage());
//        }
//    }

    /**
     * 生成用户认证码
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180901
     */
    public function userAuthQRAction()
    {
        $userId = $this->request->getPost('userId', 'int');
        $userType = $this->request->getPost('userType', 'int');
        if (!$userId) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        if (!in_array($userType, [1, 4])) {
            return $this->sendErrorResponse(400, '参数不正确');
        }
        try {
            $ips = Tool::getValue(Main::getConfigByName('admin'), 'companyIP', [], function ($ips) {
                return explode(';', $ips);
            });
            if ($ips && !in_array(Tool::getIp(), $ips)) {
                throw new \Exception('请在公司内操作');
            }

            //根据type查询教师或学生
            if ($userType == 1) {
                $info = XhsysUserstud::findFirst($userId);
                if (!$info) {
                    $info = new XhsysUserstud(['iUserId' => $userId]);
                    if (!$info->save()) {
                        throw new \Exception($info->getError());
                    }
                    $info = XhsysUserstud::findFirst($userId);
                }
            } else {
                $info = XhsysUserTch::findFirst("iUserId = {$userId}");
                if (!$info) {
                    $info = new XhsysUserTch(['iUserId' => $userId]);
                    if (!$info->save()) {
                        throw new \Exception($info->getError());
                    }
                    $info = XhsysUserTch::findFirst($userId);
                }
            }

            if (!$info->bAuthUseful) {
                throw new \Exception('不可操作');
            }
            $pwd = Tool::getValue(Main::getConfigByName('admin'), 'defaultPwd', '123456');
            if (!$info->sAuthCode) {
                $info->sAuthCode = substr(md5($userId . date('mYd') . $pwd), 0, 30);
                if (!$info->save()) {
                    throw new \Exception($info->getError());
                }
            }
            $auth = [
                'account' => User::getLogonName($userId),
                'password' => $pwd,
                'code' => $info->sAuthCode,
                'currentId' => intval(User::getId())
            ];
//            ob_start();
//            QRcode::png(json_encode($auth),false, 0, 10, 1);
//            $imgString = base64_encode(ob_get_contents());
//            ob_end_clean();
            return $this->sendSuccessResponse(Tool::getQRBase64Uri(json_encode($auth)), false);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 学生手动绑定平板
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180711
     */
    public function handBindStudTabletAction()
    {
        $studId = $this->request->getPost('userId', 'int');
        $devNumber = $this->request->getPost('devNumber', 'string');
        if (!$studId || !$devNumber) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        try {
            Device::bindTablet($studId, $devNumber);
            return $this->sendSuccessResponse('绑定成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '绑定失败', $e->getMessage());
        }
    }

    /**
     * 设置随机密码
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20181207
     */
    public function setRandomPwdAction()
    {
        $userIds = $this->request->getPost('userId', 'int');
        $hour = $this->request->getPost('hour', 'int');
        $pwd = $this->request->getPost('pwd', 'string');
        if (!$userIds) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        try {
            if (!$hour) {
                $hour = 8;
            }
            $time = $hour * 60 * 60;
            $data = UserService::setRandomPwd($userIds, $time, $pwd);
            foreach ($data as &$row) {
                $row['expiresTime'] += $row['createTime'];
            }
            unset($row);
            Tool::runTimestamp($data, ['createTime', 'expiresTime']);
            $title = [
                'userName' => '姓名',
                'logonName' => '账号',
                'realPassword' => '密码',
                'expiresTime' => '过期时间',
                'createTime' => '创建时间'
            ];
            Main::runUserName($data, ['userId' => 'userName']);
            Main::runUserLogonName($data, ['userId' => 'logonName']);

            //生成excel
            $spreadsheet = new Spreadsheet();
            $worksheet = $spreadsheet->getActiveSheet();
            Tool::setExcelData($worksheet, [$title], 1);
            $data = Tool::runExcelData($title, $data);
            Tool::setExcelData($worksheet, $data, 2);
            $fileName = Tool::buildPath(TEMP_PATH, '随机密码_' . uniqid() . '.xlsx');
            $writer = new Xlsx($spreadsheet);
            $writer->save($fileName);

            //上传
            $url = Main::uploadToFileManageSystem($fileName);
            @unlink($fileName);
            if (!$url) {
                throw new XhException('文件上传失败');
            }
            return $this->sendSuccessResponse($url);
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
        }
    }

    /**
     * 清除随机密码
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20181207
     */
    public function cleanRandomPwdAction()
    {
        $userIds = $this->request->getPost('userId', 'int');
        if (!$userIds) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        try {
            UserService::cleanRandomPwd($userIds);
            return $this->sendSuccessResponse('清除成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
        }
    }

    /**
     * 解除设备绑定
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170722
     * modify by ck 20171220    支持解除借用
     */
//    public function unbindDeviceAction()
//    {
//        $ids  = $this->request->getPost('ids', 'string');
//        $type = $this->request->getPost('type', 'int', 1);
//        if(!$ids || !$type){
//            return $this->sendErrorResponse(400, '缺少数据');
//        }
//        if (!Power::exist($type == 2 ? 'School_List_Spare' : 'School_List_Stud_Device')){
//            return $this->sendErrorResponse(403,'无操作权限');
//        }
//        $data = XhsysAccountdevicelocked::find([
//            'conditions' => 'bDelete = 0 AND iSourceType = :type: AND iADLId IN ({idArr:array})',
//            'bind'       => ['type' => $type, 'idArr' => $ids]
//        ]);
//        if (!count($data)) {
//            return $this->sendErrorResponse(400, '无可操作数据');
//        }
//        $result = $data->delete();
//        if(!$result){
//            return $this->sendErrorResponse(500, '操作失败');
//        }
//        return $this->sendSuccessResponse('操作成功');
//    }

    /**
     * 学校用户选择应用组页面
     *
     * create by ck 20160707
     * modify by ck 20160913    结构更改
     * modify by ck 20161008    js压缩
     */
    public function schoolUserChooseGroupAction()
    {
        $this->view->pick('school/schoolUserChooseGroup');
        Assets::easyUI('js/school/schoolUserChooseGroup.js');
        Template::exists('XHSchool_AppGroup', 'list') or die(Main::showMessageModal('列表配置文件不存在，请先创建！', 109106035));
        School::hasPower($this->request->getQuery('iSchoolId', 'int')) or die(Main::showMessageModal('无查看权限！', 109106053));
        $this->view->setVars(array(
            'List' => Template::createList('List', 'XHSchool_AppGroup', [
                'checkbox' => false,
                'field' => ['iSAGId', 'sSAGName', 'iSAType', 'bSAGEnable'],
                'tableAttr' => ['singleSelect' => 'true']
            ])
        ));
    }

    /**
     * 学校班级管理页面
     *
     * create by ck 20161012
     * modify by ck 20170409    更改下拉框样式，添加筛选
     */
    public function schoolClassManageListAction()
    {
        $this->view->pick('school/schoolClassManageList');
        Assets::easyUI('js/school/schoolClassManageList.js');
        Assets::select2();
        Template::exists('XHSys_User', 'list') or die(Main::showMessageModal('列表配置文件不存在！', 109106055));
        $schoolId = $this->request->getQuery('iSchoolId', 'int');
        School::hasPower($schoolId) or die(Main::showMessageModal('无查看权限！', 109106054));
        if (!Power::exist('School_List_Class')) {
            return $this->sendViewError('无班级管理权限！');
        }
        $listSearchArr = [];
        $listSearchArr[] = ['type' => 'text', 'id' => 'TeacherList_Search', 'label' => '搜索：'];
        $this->view->setVars([
            'TeacherList' => Template::createList('TeacherList', 'XHSys_User', [
                'checkbox' => false,
                'tableAttr' => ['singleSelect' => 'true', 'title' => '教师列表'],
                'field' => ['iUserId', 'sUserName', 'sLogonName'],
                'searchToolbar' => Template::createSearchToolBar($listSearchArr)
            ]),
            'schoolName' => $this->request->getQuery('sSchoolName', 'string'),
            'appList' => XhsysEnum::getEnumByNodeName('应用编号')
        ]);
    }

    /**
     * 班级升级界面
     *
     * @return bool|string
     *
     * create by ck 20170802
     */
    public function classNameUpdateAction()
    {
        $this->view->pick('school/classNameUpdate');
        Main::showNavPosition('学校列表', '班级升级');
        Assets::select2();
        Assets::easyUI('js/school/classNameUpdate.js');
        $schoolId = $this->request->getQuery('schoolId', 'int');
        if (!Power::exist('School_List_UpdateClass')) {
            return $this->sendViewError('无升级权限！');
        }
        if (!School::hasPower($schoolId, true)) {
            return $this->sendViewError('无该学校管理权限！');
        }
        $appCodeList = XhsysEnum::getEnumByNodeName('应用编号');
        $maskList = explode(',', Main::getConfigByName('maskRelation')['app']);
        foreach ($maskList as $maskAppCode) {
            unset($appCodeList[$maskAppCode]);
        }
        $this->view->setVars([
            'List' => Template::createList('List', 'School_Class', [
                'buttonToolbar' => Template::createButtonToolBar([
                    ['id' => 'bt_list_update_class', 'text' => '升级', 'plain' => 'true', 'icon' => 'fa-arrow-up']
                ])
            ]),
            'AppCode' => $appCodeList
        ]);
        return true;
    }

    /**
     * 获取班级列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170803
     */
    public function getSchoolClassAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        $appCode = $this->request->getPost('appCode', 'string');
        if (!$schoolId) {
            return $this->sendErrorResponse(400, '学校id不能为空!');
        }
        if (!$appCode) {
            return $this->response->setJsonContent(['total' => 0, 'rows' => []]);
        }
        try {
            $data = Main::transitToCppInterface('cRelation', 'Web_GetXUnitList', ['iSchoolId' => $schoolId, 'iAppCode' => $appCode, 'iFilter' => 1]);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
        if ($data['R'] != 200) {
            return $this->sendErrorResponse(500, $data['I'] ?: '师生关系错误', $data);
        }

        //处理班级列表
        $data = json_decode($data['D'], true);
        $classList = [];
        foreach ($data as $tchClass) {
            foreach ($tchClass['oClass'] as $class) {
                $classList[] = [
                    'sClassId' => $class['sClassId'],
                    'sClassName' => $class['sClassName'],
                    'iNum' => $class['iNum'],
                    'iTchId' => $tchClass['iTchId'],
                    'sTchName' => $tchClass['sTchName']
                ];
            }
        }
        return $this->response->setJsonContent(['total' => count($classList), 'rows' => $classList]);
    }

    /**
     * 设置学生班级名称
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171124
     */
    public function setClassNameAction()
    {
        $ids = $this->request->getPost('ids', 'int');
        $schoolId = $this->request->getPost('schoolId', 'int');
        $className = $this->request->getPost('className', 'string');
        if (!$ids || !$schoolId || !$className) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        try {
            $result = $this->modelsManager->executeQuery(
                'update \\Admin\\Models\\user\\XhsysUser set sAdClsName = :className: where iSchoolId = :schoolId: and iUserType = 1 and iUserId in ({ids:array})',
                ['className' => $className, 'schoolId' => $schoolId, 'ids' => $ids]
            );
            if (!$result) {
                throw new \Exception('保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 升级班级名称
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170803
     */
    public function updateClassNameAction()
    {
        if (!Power::exist('School_List_UpdateClass')) {
            return $this->sendErrorResponse(400, '无升级权限！');
        }
        $appCode = $this->request->getPost('appCode', 'string');
        $classIdArr = $this->request->getPost('classId', 'string');
        $classNameArr = $this->request->getPost('className', 'string');
        $tchIdArr = $this->request->getPost('tchId', 'int');
        if (!$classIdArr || !$classNameArr || !$tchIdArr || count($classIdArr) != count($classNameArr) || count($classIdArr) != count($tchIdArr)) {
            return $this->sendErrorResponse(400, '参数不完整！');
        }
        $result = [];
        foreach ($classIdArr as $index => $classId) {
            $result[$classId] = ['classId' => $classId, 'oldClassName' => $classNameArr[$index]];
            preg_match("/[1-8]\d{2,4}/", $classNameArr[$index], $className);
            if (empty($className)) {
                $result[$classId]['newClassName'] = '不符合转换条件';
                continue;
            }
            //班级升级
            $className = $className[0];
            $className[0] = $className[0] + 1;
            try {
                $data = Main::transitToCppInterface('cRelation', 'Web_ChangeClassInfo',
                    ['iAppCode' => $appCode, 'iTchId' => $tchIdArr[$index], 'sClassId' => $classId, 'sClassName' => $className]);
                if ($data['R'] != 200) {
                    $result[$classId]['newClassName'] = '转换失败：' . $data['I'];
                    continue;
                }
                $result[$classId]['newClassName'] = $className;
            } catch (\Exception $e) {
                $result[$classId]['newClassName'] = '转换失败：' . $e->getMessage();
            }
        }
        return $this->response->setJsonContent($result);
    }

    /**
     * 同步应用组
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170812
     */
    public function synAppGroupAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        if (!$schoolId) {
            return $this->sendErrorResponse(400, '缺少学校ID！');
        }
        $config = Main::getConfigByName('jAppServer');
        $httpClient = (new HttpClient($config['url']))->fullResponse();

        try {
            //处理新应用列表
            $appServerController = new AppserverController();
            $_POST['rows'] = 1000;
            $appServerController->initialize();
            $appSourceArr = $appServerController->getApplicationAction()->getContent();
            $appSourceArr = json_decode($appSourceArr, true);
            if (isset($appSourceArr['error'])) {
                return $this->response->setJsonContent($appSourceArr, JSON_UNESCAPED_UNICODE);
            }
            $appSourceArr = array_column($appSourceArr['rows'], 'versionCode', 'packageName');

            //连接学校数据库查询组信息
            $dbName = null;
            $conn = Main::getSchoolMainDB($schoolId, $dbName);
//            $groupArr = $conn->fetchAll("select us_id as groupId,us_name as groupName from users where us_flag = 88 and us_state = 0 and us_school_xxid = {$schoolId}");
            $groupArr = $conn->fetchAll("select us_id as groupId,us_name as groupName from users where us_flag = 88 and us_state = 0");
            if (!$groupArr) {
                return $this->sendErrorResponse(200, '该学校无应用组！');
            }
            $groupArr = array_column($groupArr, null, 'groupId');
            foreach ($groupArr as $groupId => $group) {
                $groupArr[$groupId]['userNum'] = 0;
                $groupArr[$groupId]['totalApp'] = 0;
                $groupArr[$groupId]['matchApp'] = 0;

                //查询用户创建用户组
                $userIdList = $conn->fetchAll("select us_id as id from users where us_groupid = {$groupId} and us_state = 0");
                if (!$userIdList) {
                    $groupArr[$groupId]['msg'] = '无用户，跳过';
                    continue;
                }
                $groupArr[$groupId]['userNum'] = count($userIdList);
                $response = $httpClient->postJson('/api/v1/groups/',
                    ['groupName' => $group['groupName'], 'schoolId' => intval($schoolId), 'userType' => 4, 'userIdList' => $userIdList]);
                if (!$response->isSuccess()) {
                    $body = $response->toObject();
                    $groupArr[$groupId]['msg'] = '创建失败：' . $body->msg;
                    continue;
                }

                //获取新用户组id
                $newGroupId = explode('/', $response->responseHeader['Location']);
                $newGroupId = end($newGroupId);

                //获取组应用列表
                $groupAppList = $conn->fetchAll("select sy_name4 as packageName from system_type where sy_type = 'systemapplist' and sy_state = 0 and sy_name1 <> 'so' and sy_id in (select ap_sy_id from app_group_power where ap_gr_id = {$groupId} and ap_state = 0)");
                if (!$groupAppList) {
                    $groupArr[$groupId]['msg'] = '成功，无应用';
                    continue;
                }
                $groupArr[$groupId]['totalApp'] = count($groupAppList);

                //用户组添加应用
                $postPackage = [];
                foreach ($groupAppList as $appInfo) {
                    $packageName = explode('|', $appInfo['packageName'])[0];
                    if (isset($appSourceArr[$packageName])) {
                        $postPackage[] = ['packageName' => $packageName, 'versionCode' => intval($appSourceArr[$packageName])];
                    }
                }
                $groupArr[$groupId]['matchApp'] = count($postPackage);

                $response = $httpClient->postJson(sprintf('/api/v1/initiate/groups/%s/apps', $newGroupId), $postPackage);
                if (!$response->isSuccess()) {
                    $body = $response->toObject();
                    $groupArr[$groupId]['msg'] = '添加应用失败：' . $body->msg;
                    continue;
                }
                $groupArr[$groupId]['msg'] = '成功';
            }
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
        return $this->sendJsonResponse(array_values($groupArr));
    }

    /**
     * 刷新用户登陆信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170814
     * modify by ck 20180903    更改新缓存刷新
     */
    public function refreshLoginInfoAction()
    {
        $userIds = $this->request->getPost('userIds', 'int');
        if (!$userIds) {
            return $this->sendErrorResponse(400, '缺少用户id！');
        }
        try {
//            Main::refreshUserLogin($userIds);
            Auth::refresh($userIds);
            return $this->sendSuccessResponse('刷新成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
//        $url = Main::getConfigByName('cLogin')['url'];
//        if (!$url){
//            return $this->sendErrorResponse(500, '缺少登陆url！');
//        }
//        $httpClient = new HttpClient($url);
//        $response = $httpClient->post('/refreshUserInfo',
//            ['K' => json_encode(['type' => 'batch', 'oUserId' => implode(',', $userIds)])]);
//        $body = $response->toArray();
//        if (!isset($body['R']) || $body['R'] != 200){
//            return $this->sendErrorResponse(500, '刷新失败！', $body['I'] ?: $body);
//        }
//        return $this->sendSuccessResponse('刷新成功！');
    }

    /**
     * 根据学校及类型刷新缓存
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180920
     */
    public function refreshSchoolLoginAction()
    {
        $schoolIds = $this->request->getPost('schoolIds', 'int');
        $userType = $this->request->getPost('userType', 'int');
        if (!$schoolIds) {
            return $this->sendErrorResponse(400, '缺少学校');
        }
        try {
            $params = [
                'columns' => 'iUserId',
                'conditions' => 'bDelete = 0 AND iSchoolId IN ({schoolId:array})',
                'bind' => ['schoolId' => $schoolIds]
            ];
            if ($userType) {
                $params['conditions'] .= ' AND iUserType = :userType:';
                $params['bind']['userType'] = $userType;
            }
            $users = XhsysUser::find($params)->toArray();
            if (count($users) <= 0) {
                return $this->sendErrorResponse(400, '无需处理');
            }
            $userIds = array_column($users, 'iUserId');
            Auth::refresh($userIds);
            return $this->sendSuccessResponse(sprintf('成功刷新%d用户', count($userIds)));
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
        }

    }

    /**
     * 跳转到学校管理页面
     *
     * create by ck 20170827
     * modify by ck 20171122
     * modify by ck 20180711
     */
    public function schoolManageAction()
    {
        $schoolId = $this->request->getQuery('schoolId', 'int');
        $tchId = $this->request->getQuery('tchId', 'int');
        $direction = $this->request->getQuery('direction', 'string');
        if ($tchId) {
            $direction = 'teacher';
        }

        $authFun = function ($data = [], $key = 'xuehai1234') {
            ksort($data);
            $sign = md5(implode('|', $data) . $key);
            $paramArr = array_merge($data, ['sign' => $sign]);
            return http_build_query($paramArr);
        };

        $data = [
            'userId' => $tchId ?: User::getId(),
            'schoolId' => $schoolId,
            'direction' => $direction,
            't' => time() + 120,
            'loginUserId' => User::getId()
        ];

        $url = Main::getConfigByName($tchId ? 'tchManage' : 'schoolManage')['url'];
//        $userId   = $tchId ?: User::getId();
//        $time     = time() + 120;
//        $key      = md5("xuehai1234{$time}|{$userId}|{$schoolId}|{$direction}");
//        return $this->response->redirect("{$url}/school/Index/authLogin?key={$key}&userId={$userId}&schoolId={$schoolId}&direction={$direction}&t={$time}");
        return $this->response->redirect("{$url}/school/Index/authLogin?" . $authFun($data));
    }

    /**
     * 教师数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 20171106
     */
    public function getTchDataAction()
    {
//        $iUserType = $this->request->getPost('iUserType') or $iUserType =4;
        $iSchoolId = $this->request->getPost('iSchoolId');
        $key = $this->request->getPost('key');
        $startTime = $this->request->getPost('startTime');
        $endTime = $this->request->getPost('endTime');
        $order = $this->request->getPost('order');
        $sort = $this->request->getPost('sort');
        $type = $this->request->getPost('type');
        $log = $this->request->getPost('log');
        $subject = $this->request->getPost('subject');
        $schCity = $this->request->getPost('schCity');
        $schArea = $this->request->getPost('schArea');
        $trackType = $this->request->getPost('trackType');
        $history = $this->request->getPost('history', 'int', 0);
        $grade = $this->request->getPost('grade', 'string');
        $important = $this->request->getPost('important', 'string');
        $excellent = $this->request->getPost('excellent', 'string');
        try {

            $sql = "select tTime,iUserId,tLastModifyDate,iSchoolId,sTypes from XHLog_UserTch  order by  tTime desc  ";
            $sql = "select tk.* from ({$sql}) as tk   group by tk.iUserId";//取最近的一条修改记录
            $sql = " select u.iUserId,u.iUserType,u.sUserName,u.sLogonName,u.iUserSex,u.iSchoolId,s.sSchoolName,lt.tTime,lt.sTypes,ut.iProficiency,ut.iSubject,ut.iCurGrade,ut.bExcellent,ut.bImportant from XHSys_User as u   " .
                " left join XHSchool_Info as s on u.iSchoolId = s.iSchoolId " .
                " left join  XHSys_UserTch as ut on u.iUserId=ut.iUserId" .
                " left join ({$sql}) as lt on lt.iUserId = u.iUserId where u.iUserType = 4 and  u.bDelete = 0 and u.bDisable = 0 and u.bHistory = {$history} ";
//                " left join ({$sql}) as lt on lt.iUserId = u.iUserId where u.iUserType = 4 and  u.bDelete = 0 and u.bCompany = 0 and u.bDisable = 0 and u.bHistory = {$history} ";

            $sql = " select :columns: from ({$sql}) as td ";
            $conditionArr = [];
//            $conditionArr[] = 'td.iUserType ='.$iUserType.' ';
            if ($iSchoolId) {
                $conditionArr[] = " td.iSchoolId = " . $iSchoolId . " ";
                $check = XhsysUser::findFirst([
                    'columns' => 'iUserId',
                    'conditions' => 'bDelete=0 AND iSchoolId=:iSchoolId:',
                    'bind' => ['iSchoolId' => $iSchoolId],
                ]);
                if (!$check) {
                    return json_encode(['rows' => 0, 'data' => []]);
                }
            } else { //没有学校id传入时
                $staff = false;
                if ($schCity || $schArea) {
                    $depId = $schCity ?: $schArea;
                    $staff = $this->db->fetchOne("select iUserId as userId from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$depId},%'");
                }
                $schoolIds = School::getPower(false, $staff ? $staff['userId'] : null);
//                if($schArea&&$schCity){
//
//                    $staffSql = "select  iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$schCity},%'"; //取第一个
//                    $staffs = $this->db->query($staffSql)->fetchAll(\PDO::FETCH_ASSOC);
//                    $authId = !isset($staffs[0]['iUserId']) ?  null : $staffs[0]['iUserId'];
//                    $schoolIds = School::getPower(false,$authId);
//                }else if($schArea){
//                    $staffSql = "select  iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$schArea},%'"; //取第一个
//                    $staffs = $this->db->query($staffSql)->fetchAll(\PDO::FETCH_ASSOC);
//                    $authId = !isset($staffs[0]['iUserId']) ?  null : $staffs[0]['iUserId'];
//                    $schoolIds = School::getPower(false,$authId);
//
//                }else{
//                    $schoolIds = School::getPower(false);
//                }

                if (!$schoolIds) {
                    return $this->sendDataGridError('无学校权限');
                } else if ($schoolIds !== true) {
                    $conditionArr[] = ' td.iSchoolId IN (' . implode(',', $schoolIds) . ') ';
                }
            }

            if ($trackType) {
                $trackSql = "select iTrackType,iUserId from XHTrack_Tch where bDelete=0 AND iTrackType = {$trackType}   order by  tCreateDate desc ";
                $trackSql = "select tk.* from ({$trackSql}) as tk   group by tk.iUserId";
                $trackUserId = $this->db->fetchAll($trackSql);
                $trackUserId = array_column($trackUserId, 'iUserId');
                if (count($trackUserId) != 0) {
                    $conditionArr[] = ' td.iUserId IN (' . implode(',', $trackUserId) . ') ';
                } else {
                    return $this->sendJsonResponse(['total' => 0, 'rows' => []]);
                }

            }

            if ($key) {
                $conditionArr[] = " td.sUserName like '%" . $key . "%' OR td.sLogonName like '%" . $key . "%' ";
            }
            if ($subject) {
                $conditionArr[] = " td.iSubject = {$subject} ";
            }

            if ($grade) {
                $conditionArr[] = " td.iCurGrade = {$grade} ";
            }

            if ($important) {
                $important = $important - 1;
                $conditionArr[] = "td.bImportant = {$important} ";
            }

            if ($excellent) {
                $excellent = $excellent - 1;
                $conditionArr[] = "td.bExcellent = {$excellent} ";
            }

            if ($type == 1) { //全部

            } else { //有更新
                if ($startTime & $endTime && $log) {
                    $userSql = "select tTime,iUserId,tLastModifyDate,iSchoolId,sTypes from XHLog_UserTch Where tTime >= '" . $startTime . "' AND  tTime <= '" . $endTime . "' AND sTypes  like '%," . $log . ",%' ";
                } else if (!$log) {
                    $userSql = "select tTime,iUserId,tLastModifyDate,iSchoolId,sTypes from XHLog_UserTch Where tTime >= '" . $startTime . "' AND  tTime <= '" . $endTime . "' ";
                }
                $userData = $this->db->query($userSql)->fetchAll(\PDO::FETCH_ASSOC);
                $iUserIds = array_values(array_unique(array_filter(array_column($userData, 'iUserId'))));
                if ($iUserIds != []) {
                    if ($type == 2) {  //无更新
                        $conditionArr[] = 'td.iUserId not IN (' . implode(',', $iUserIds) . ') ';
                    } else if ($type == 3) {
                        $conditionArr[] = 'td.iUserId  IN (' . implode(',', $iUserIds) . ') ';
                    }
                } else {
                    if ($type == 3) {
                        return json_encode(['rows' => 0, 'data' => [], 'error' => '没有更新记录']);
                    }
                }
            }


            if ($conditionArr != []) {
                $conditionStr = implode(' AND ', $conditionArr);
                $sql .= 'where ' . $conditionStr;
            }


            if ($order && $sort) {
                $sql .= " ORDER BY td." . $sort . " " . $order;
            } else {
                $sql .= " ORDER BY td.iUserId";
            }

            $data = Main::runSqlPage(['query' => $sql, 'columns' => 'td.*'], $this->userEnum);
            $iCurGrade = XhsysEnum::getEnumByNodeName('年级');
            $iSubject = XhsysEnum::getEnumByNodeName('学科');
            $iProficiency = XhsysEnum::getEnumByNodeName('熟练程度');
            $ids = array_column($data['rows'], 'iUserId');
            $tracks = $this->getTchTrack($ids);
            foreach ($data['rows'] as $index => $row) {
                if (isset($tracks[$row['iUserId']])) {
                    $data['rows'][$index]['extra'] = $tracks[$row['iUserId']];
                    //判断是否当天
                    if ($tracks[$row['iUserId']]['tTrackTime'] == date('Y-m-d', time())) {
                        $data['rows'][$index]['extra']['flag'] = true;
                    } else {
                        $data['rows'][$index]['extra']['flag'] = false;
                    }
                } else {
                    $data['rows'][$index]['extra'] = null;
                }
                if ($row['iCurGrade']) {
                    $data['rows'][$index]['iCurGrade'] = $iCurGrade[$row['iCurGrade']];
                }
                if ($row['iSubject']) {
                    $data['rows'][$index]['iSubject'] = $iSubject[$row['iSubject']];
                }

                if ($row['iProficiency']) {
                    $data['rows'][$index]['iProficiency'] = $iProficiency[$row['iProficiency']];
                }
                $data['rows'][$index]['tchIcon'] = '<i class="fa fa-user" style="color:blue;"></i>';
                if ($row['bExcellent'] == 1) {
                    $data['rows'][$index]['tchIcon'] = '<i class="fa fa-user" style="color:red;"></i>';
                }
                if ($row['bImportant'] == 1) {
                    $data['rows'][$index]['tchIcon'] = '<i class="fa fa-user" style="color:green;"></i>';
                }
            }

//            if ($trackType){
//                foreach ($data['rows'] as $index=>$row){
//                    if(!$data['rows'][$index]['extra']){
//                        unset($data['rows'][$index]);
//                    }else if($data['rows'][$index]['extra']['iTrackType'] != $trackType){
//                        unset($data['rows'][$index]);
//                    }
//                }
//                $data['rows'] = array_values($data['rows']);
//                $data['total'] = count($data['rows']);
//            }
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            die($e->getMessage());
        }
    }

    public function getSchForTchAction()
    {

        $startTime = $this->request->getPost('startTime');
        $endTime = $this->request->getPost('endTime');
        $key = $this->request->getPost('key');
        $sort = $this->request->getPost('sort');
        $order = $this->request->getPost('order');
        $state = $this->request->getPost('schState');
        $schCity = $this->request->getPost('schCity');
        $schArea = $this->request->getPost('schArea');

        $title1 = '';
        try {
            if ($startTime && $endTime) {
                $title1 .= "更新区间:{$startTime}-{$endTime}";
                $sql = "select count(DISTINCT(l.iUserId)) as schoolInfo,l.iSchoolId from  XHLog_UserTch as l where l.sTypes LIKE '%,2,%' AND l.tTime>='{$startTime}' AND l.tTime<='{$endTime}'  GROUP BY l.iSchoolId ";
            } else {
                $time = date('Y-m-d', time());
                $title1 .= "更新区间:{$time}";
                $sql = "select count(DISTINCT(l.iUserId)) as schoolInfo,l.iSchoolId from  XHLog_UserTch as l where l.sTypes LIKE '%,2,%' AND l.tTime='{$time}'  GROUP BY l.iSchoolId ";
            }
            //筛选学校权限
            $authId = null;
            if ($schArea) {
                $condition = $schCity ?: $schArea;
                $staffSql = "select  iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$condition},%'"; //取第一个
                $staffs = $this->db->fetchAll($staffSql);
                $authId = !isset($staffs[0]['iUserId']) ? null : $staffs[0]['iUserId'];
            }

            $schoolIds = School::getPower(false, $authId);
            $schoolConditions = '';
            if (!$schoolIds) {
                return $this->sendDataGridError('无学校权限');
            } else if ($schoolIds !== true) {
                $schoolConditions = ' AND s.iSchoolId IN (' . implode(',', $schoolIds) . ') ';
            }
            $sql = "select s.iSchoolId,s.sSchoolName,i.schoolInfo  from XHSchool_Info as s " .
                " LEFT JOIN ({$sql}) as i ON s.iSchoolId=i.iSchoolId  WHERE s.bDelete=0 " . $schoolConditions;
            if ($key) {
                $sql .= "AND sSchoolName like '%{$key}%' ";
            }
            if ($state) {
                $sql .= "AND iStatus =  {$state} ";
            }
            if ($sort && $order) {
                $sql .= 'ORDER BY ' . $sort . '  ' . $order;
            }
            $data = Main::runSqlPage(['query' => "select :columns: from ({$sql}) as td", 'columns' => 'td.*']);

            $ids = implode(',', array_column($data['rows'], 'iSchoolId'));
            $tchNum = $this->getTchNum($ids);
            $checkNum = $this->getCheckNum($ids);
            if (array_column($data['rows'], 'iSchoolId') != []) {
                //获取最近更新的时间。
                $sql1 = "select tTime,iUserId,iSchoolId,tCreateDate from XHLog_UserTch WHERE iSchoolId in ({$ids}) order by tCreateDate desc";
                $sql1 = "select t.* from ({$sql1}) as t  GROUP BY t.iUserId ORDER BY tTime DESC ";
                $sql1 = "select s.iSchoolId,s.tTime from ({$sql1})  as s  GROUP BY s.iSchoolId ";
                $times = $this->db->query($sql1)->fetchAll(\PDO::FETCH_ASSOC);
                $times = array_column($times, 'tTime', 'iSchoolId');
            } else {
                $times = [];
            }

            foreach ($data['rows'] as $index => $row) {
                $title = "学校id:{$row['iSchoolId']}," . $title1;

                if (isset($times[$row['iSchoolId']])) {
                    $title .= '最近跟踪时间:' . $times[$row['iSchoolId']];
                } else {
                    $title .= '不存在最近跟踪';
                }
                $data['rows'][$index]['iTchNum'] = $tchNum[$row['iSchoolId']] ?: 0;
                if (isset($checkNum[$row['iSchoolId']])) {
                    $data['rows'][$index]['schoolCheck'] = '<small class="badge   badge-square " ><span style="color: green">' . $checkNum[$row['iSchoolId']]['checkNum'] . '</span>/<span style="color: red">' . $checkNum[$row['iSchoolId']]['uncheckNum'] . '</span></small>';
                } else {
                    $data['rows'][$index]['schoolCheck'] = '';
                }
                if ($row['schoolInfo']) {
                    $data['rows'][$index]['schoolInfo'] = '<small class="badge badge-success  badge-square " title="' . $title . '">' . $row['schoolInfo'] . '</small>';
                } else {
                    $data['rows'][$index]['schoolInfo'] = '<small class="badge badge-danger badge-square " title="' . $title . '">0</small>';
                }
            }
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            die($e->getMessage());
        }

    }

    /**
     * 获取教师数目
     *
     * @param $idsStr
     * @return array
     *
     * created by dale 2017125
     */
    public function getTchNum($idsStr)
    {
        if ($idsStr == '') {
            return [];
        }
//        $ids  = explode(',',$idsStr);

//        $sql    = "select count(iUserId) as num,iSchoolId from XHSys_User WHERE  iUserType = 4 and  bDelete = 0 and bCompany = 0 and bDisable = 0 and bHistory = 0 AND iSchoolId in  ({$idsStr})  GROUP BY iSchoolId";
        $sql = "select count(iUserId) as num,iSchoolId from XHSys_User WHERE  iUserType = 4 and  bDelete = 0 and bDisable = 0 and bHistory = 0 AND iSchoolId in  ({$idsStr})  GROUP BY iSchoolId";
        $tchNum = $this->db->fetchAll($sql);
        return array_column($tchNum, 'num', 'iSchoolId');
    }

    /**
     * 获取审批的数目
     *
     * @param $idsStr
     * @return array
     *
     * created by dale 2017125
     */
    public function getCheckNum($idsStr)
    {
        if ($idsStr == '') {
            return [];
        }
        $ids = explode(',', $idsStr);
        try {
            $now = date('Y-m-d', time());
            $sql1 = "select t.iTTchId,t.iUserId,t.iState,t.tCreateDate,u.iSchoolId from XHTrack_Tch as t" .
                " LEFT JOIN  XHSys_User as u  on u.iUserId = t.iUserId" .
                " WHERE DATE_FORMAT(t.tCreateDate,'%Y-%m-%d') = '{$now}' AND t.iState != 2 AND u.iSchoolId in ({$idsStr})";

            $sql2 = "select t.iTTchId,t.iUserId,t.iState,t.tCreateDate,u.iSchoolId from XHTrack_Tch as t" .
                " LEFT JOIN  XHSys_User as u  on u.iUserId = t.iUserId" .
                " WHERE DATE_FORMAT(t.tCreateDate,'%Y-%m-%d') = '{$now}' AND t.iState = 2 AND u.iSchoolId in ({$idsStr})";
            $sql1 = "select count(t.iUserId) as num,t.iSchoolId from ({$sql1}) as t ";
            $sql2 = "select count(t.iUserId) as num,t.iSchoolId from ({$sql2}) as t ";
            $checkNum = array_column($this->db->fetchAll($sql2), 'num', 'iSchoolId');
            $uncheckNum = array_column($this->db->fetchAll($sql1), 'num', 'iSchoolId');
            $arr = [];
            foreach ($ids as $id) {
                $arr[$id]['checkNum'] = $checkNum[$id] ?: 0;
                $arr[$id]['uncheckNum'] = $uncheckNum[$id] ?: 0;
            }
            return $arr;
        } catch (\Exception $e) {
            die($e->getMessage());
        }
    }


    /**
     * tchTrack数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 2017/11/7
     */
    private function getTchTrack($ids)
    {
        $str = implode(',', $ids);
        if ($ids == []) {
            return [];
        }
        $sql = "select max(iTTchId) from XHTrack_Tch where bDelete= 0 group by iUserId ";
//        $sql  = "select iUserId,tCreateDate,mContent,tTrackTime,IFNULL(mAppUse,'') as mAppUse,IFNULL(mPurpose,'') as mPurpose,IFNULL(mResult,'') as mResult,iState,IFNULL(mCheck,'') as mCheck,iTrackType from XHTrack_Tch where bDelete=0 AND iUserId in ({$str}) order by  tCreateDate desc limit 10000 ";
//        $sql  = "select tk.* from ({$sql}) as tk   group by tk.iUserId";
//        var_dump($this->db->fetchAll($sql));die;
        $sql = "select iTTchId,iUserId,tCreateDate,mContent,tTrackTime,IFNULL(mAppUse,'') as mAppUse,IFNULL(mPurpose,'') as mPurpose,IFNULL(mResult,'') as mResult,iState,IFNULL(mCheck,'') as mCheck,iTrackType from XHTrack_Tch where iTTchId in ({$sql}) ";
        $data = $this->db->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
        $trackType = XhsysEnum::getEnumByNodeName('教师跟踪类型');
        foreach ($data as $index => $row) {
            $data[$index]['tTrackTime'] = date('Y-m-d', strtotime($row['tTrackTime']));
            if ($data[$index]['iTrackType']) {
                $data[$index]['iTrackType'] = $trackType[$data[$index]['iTrackType']];
            }
        }
        $data = array_column($data, null, 'iUserId');

        return $data;
    }


    /**
     * 跳转到老数据中心（题库）
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     *
     * create by ck 20171204
     */
    public function redirectOldCenterAction()
    {
        $config = Main::getConfigByName('manage_old');
        if (!$config) {
            return $this->sendViewError('缺少配置信息，请联系管理员');
        }
        return $this->response->redirect(sprintf('http://data.yunzuoye.net/prog/do_login.php?user=%s&passwd=%s&encode=1&vc=гvcг', base64_encode($config['user']), base64_encode($config['password'])), true);
    }

    /**
     * 跳转到学校老后台
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     *
     * create by ck 20171205
     */
    public function redirectOldSchoolAction()
    {
        $schoolId = $this->request->getQuery('schoolId', 'int');
        if (!$schoolId) {
            return $this->sendViewError('缺少学校id');
        }
        $config = Main::getConfigByName('manage_old');
        if (!$config) {
            return $this->sendViewError('缺少配置信息，请联系管理员');
        }
        $conn = new Mysql(Main::getConfigByName('oldCenterDB'));
        $info = $conn->fetchOne("select sy_name3 from system_type where sy_type = 'szxx' and sy_id = '{$schoolId}'")['sy_name3'];
        $info = explode('|', $info);
        return $this->response->redirect(sprintf('http://%s/prog/do_login.php?user=%s&passwd=%s&encode=1&vc=гvcг', $info[2], base64_encode($config['user']), base64_encode($config['password'])), true);
    }

    /**
     * 学生借用平板页面
     *
     * @return View
     *
     * create by ck 20171219
     */
    public function studBorrowTabletAction()
    {
        $this->view->setTemplateBefore('listForm');
        Assets::easyUI('js/school/studBorrowTablet.js');
        $listSearchArr = [];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague'];
        return $this->view->setVars([
            'List' => Template::createList('list', 'School_StudBorrowTablet', [
                'checkbox' => false,
                'searchToolbar' => Template::createSearchToolBar($listSearchArr)
            ]),
        ]);
    }

    /**
     * 学生平板列表-借用
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171219
     */
    public function getStudTabletForBorrowAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        if (!$schoolId) {
            return $this->sendDataGridError('缺少学校id');
        }
        try {
            $conditions = "AND b.iSourceType = 1 AND b.bDelete = 0";
            Main::runSearchVagueConditions($conditions, ['a.iUserId', 'a.sUserName', 'a.sLogonName', 'a.sAdClsName', 'b.sDeviceNumber', 'b.sModel']);
            $sql = [
                'columns' => 'a.iUserId,a.sUserName,a.sLogonName,a.sAdClsName,a.iUserSex,b.iADLId,b.sDeviceNumber,b.sModel,b.sIP,b.sMac,b.tCreateDate',
                'query' => "SELECT :columns: FROM XHSys_User a LEFT JOIN XHSys_AccountDeviceLocked b 
                ON a.iUserId = b.iUserId AND a.iSchoolId = '{$schoolId}' AND a.iUserType = 1 AND a.bDelete = 0 AND a.bDisable = 0 AND a.bHistory = 0
                WHERE a.iUserId NOT IN (
                  SELECT iUserId FROM XHSys_AccountDeviceLocked WHERE bDelete = 0 AND iSourceType <> 1 
                ) {$conditions}"];
            return $this->sendJsonResponse(Main::runSqlPage($sql, $this->userEnum));
        } catch (\Exception $e) {
            return $this->sendDataGridError($e->getMessage());
        }
    }

    /**
     * 学生绑定平板页面
     *
     * @return View
     *
     * create by ck 20180530
     */
    public function studBindTabletAction()
    {
        $this->view->setTemplateBefore('listForm');
        Assets::easyUI('js/school/studBindTablet.js');
        $listSearchArr = [];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague'];
        return $this->view->setVars([
            'List' => Template::createList('list', 'School_StudBindTablet', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr)
            ]),
        ]);
    }

    /**
     * 获取未绑定学生列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180530
     */
    public function getUnbindStudAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        if (!$schoolId) {
            return $this->sendDataGridError('缺少学校id');
        }
        try {
            $conditions = ' ';
            Main::runSearchVagueConditions($conditions, ['iUserId', 'sUserName', 'sLogonName', 'sAdClsName']);
            $sql = [
                'columns' => 'iUserId,sUserName,sLogonName,sAdClsName,iUserSex',
                'query' => "SELECT :columns: FROM XHSys_User WHERE iSchoolId = '{$schoolId}' AND iUserType = 1 AND bDelete = 0 AND bDisable = 0 AND bHistory = 0
                  AND iUserId NOT IN (SELECT iUserId FROM XHSys_AccountDeviceLocked WHERE bDelete = 0 ) {$conditions}"
            ];
            return $this->sendJsonResponse(Main::runSqlPage($sql, $this->userEnum));
        } catch (\Exception $e) {
            return $this->sendDataGridError($e->getMessage());
        }
    }

    /**
     * 学生绑定平板
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180530
     */
    public function bindStudTabletAction()
    {
        $targetId = $this->request->getPost('targetId', 'int');
        $userIds = $this->request->getPost('userIds', 'int');
        if (!$targetId) {
            return $this->sendErrorResponse(400, '缺少用户目标id');
        }
        if (!$userIds) {
            return $this->sendErrorResponse(400, '缺少学生id');
        }
        if (!Power::exist('School_List_Stud_Bind')) {
            return $this->sendErrorResponse(403, '无操作权限');
        }
        try {
            $this->db->begin();
            $bindDev = Device::getBindTablet($targetId);
            if (!$bindDev) {
                return $this->sendErrorResponse(400, '目标学生没有绑定设备');
            }
            $maxBind = Tool::getValue(Main::getConfigByName('admin'), 'maxBindDev', 4);
            $bindNum = Device::tabletBindNum($bindDev['sDeviceNumber']);
            if ($bindNum + count($userIds) > $maxBind) {
                throw new \Exception('该设备已绑定' . $bindNum . '台，继续绑定将超出最大限制');
            }
            unset($bindDev['iADLId'], $bindDev['iUserId'], $bindDev['sLogonName']);
            $logonNames = XhsysUser::getUserLogonName($userIds);
            foreach ($userIds as $userId) {
                $obj = new XhsysAccountdevicelocked($bindDev);
                $obj->iUserId = $userId;
                $obj->sLogonName = $logonNames[$userId];
                if (!$obj->save()) {
                    throw new \Exception($obj->getError());
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('绑定成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 修改用户姓名
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180828
     */
    public function setUserNameAction()
    {
        $userId = $this->request->getPost('userId', 'int');
        $name = $this->request->getPost('name', 'string');
        if (!$userId || !$name) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        try {
            UserService::changeName($userId, $name);
            return $this->sendSuccessResponse('修改成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, '修改失败', $e->getDescription());
        }
    }

    /**
     * 修改用户性别
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180914
     */
    public function setUserSexAction()
    {
        $userId = $this->request->getPost('userId', 'int');
        $sex = $this->request->getPost('sex', 'int', 0);
        if (!$userId) {
            return $this->sendErrorResponse(400, '缺少用户id');
        }
        try {
            $user = XhsysUser::findFirst($userId);
            if (!$user) {
                throw new XhException('找不到用户');
            }
            $user->iUserSex = $sex;
            if (!$user->save()) {
                throw new XhException($user->getError());
            }
            return $this->sendSuccessResponse('修改成功');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, '修改失败', $e->getMessage());
        }
    }

    /**
     * 获取学校权限列表（有权限排序在前）
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180108
     */
//    public function getSchoolForExtraAction()
//    {
//        $userId = $this->request->getPost('userId', 'int');
//        $target = $this->request->getPost('target', 'string');
//        if (!$userId || !$target || !in_array($target, ['view', 'manage'])) {
//            return $this->sendErrorResponse(400, '');
//        }
//        try {
//            $schoolIds = User::getSchool();
//            if (!$schoolIds) {
//                return $this->sendDataGridError('无学校权限');
//            }
//            $schoolIds  = implode(',', $schoolIds);
//            $parameters = [
//                'columns'    => 'iSchoolId,sSchoolName,iStatus,bWelfare,sAbbr,iStage,iRunLevel,iType,sCode,iApprovalStatus',
//                'conditions' => "bDelete = 0 AND (iStatus = 1 OR iStatus = 2) AND iSchoolId IN ({$schoolIds})",
////                'bind'       => ['idArr' => $schoolIds]
//            ];
//            Main::runSearchVagueConditions($parameters['conditions'], ['iSchoolId', 'sSchoolName']);
//            $this->runEnum();
//            $data = Main::runModelPage('\\Admin\\Models\\school\\XhschoolInfo', $parameters, $this->schEnum);
//            $power = UserPower::getExtraSchoolPower($userId);
//            if ($power === false) {
//                $power = [];
//            } else {
//                $power = $power[$target]['id'];
//            }
//            $sort = [];
//            foreach ($data['rows'] as $row) {
//                if (in_array($row['iSchoolId'], $power)) {
//                    $sort[] = 1;
//                } else {
//                    $sort[] = 0;
//                }
//            }
//            array_multisort($sort, SORT_DESC, $data['rows']);
//            return $this->sendJsonResponse($data);
//        }
//        catch (\Exception $e) {
//            return $this->sendErrorResponse(500, $e->getMessage());
//        }
//    }

    /**
     * 获取学校权限
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180108
     */
//    public function getSchoolPowerAction()
//    {
//        $userId = $this->request->getPost('userId', 'int');
//        $power = UserPower::getExtraSchoolPower($userId);
//        if ($power === false) {
//            $power = ['view' => ['all' => false, 'id' => []], 'manage' => ['all' => false, 'id' => []]];
//        }
//        return $this->sendJsonResponse($power);
//    }

    /**
     * 学校选择页面（提供回调）
     *
     * @return View|string
     *
     * create by ck 20180124
     */
    public function schoolChooseAction()
    {
        $callback = $this->request->getQuery('callback', 'string');
        if (!$callback) {
            return $this->sendViewError('缺少回调');
        }
        $this->view->setTemplateBefore('listForm');
        Assets::easyUI('js/school/schoolChoose.js');
        $listSearchArr = [];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_search_vague', 'label' => ' 搜索： '];
        return $this->view->setVars([
            'List' => Template::createList('list', 'XHSchool_Info', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr),
                'tableAttr' => [
                    'singleSelect' => $this->request->getQuery('single', 'string', 'false') == 'true' ?: 'false'
                ]
            ])
        ]);
    }

    public function schoolBookVerAction()
    {
//	    if (!Power::exist('Res_AreaBookVerList_Edit')) {
//		    return $this->sendViewError('无修改权限');
//	    }
        $schoolId = $this->request->getQuery('schoolId');
//	    $schoolId = 2747;
        Assets::select2();
        Assets::easyUI('js/school/modifyAreaGroupForm.js');
        $this->view->pick('school/modifyAreaGroupForm');

        $schoolData = XhschoolInfo::findFirst(['conditions' => 'bDelete = 0 and iSchoolId = :iSchoolId:', 'bind' => ['iSchoolId' => $schoolId]]);
        if (!$schoolData) {
            return $this->sendViewError('没有学校数据');
        }
        $schoolData = $schoolData->toArray();
        try {
//		    $groupId = 0;
//		    if ($schoolData['sProvinceName'] && $schoolData['sCityName'] && $schoolData['sCountyName']){
//			    $existGroup = true;
//			    $params['stageType'] = $schoolData['iStage'];
//			    $params['provinceName'] = $schoolData['sProvinceName'];
//			    $params['cityName'] = $schoolData['sCityName'];
//			    $params['districtName'] = $schoolData['sCountyName'];
//			    $params['page'] = 1;
//			    $params['size'] = 10;
//			    $data = ResAreaGroup::getAreaGroupData($params);//var_dump($data);die;
//			    if ($data['totalCount'] == 0){
//				    $existGroup = false;
//			    } else {
//				    $data = $data['groupInfoListResponseList'];
//				    $groupId = $data[0]['groupId'];
//			    }
//		    } else {
//			    $existGroup = false;
//		    }
//		    $groupName = $existGroup == false ? '未找到区域组，请联系教学部设置区域组对应的教材版本！' : $data[0]['groupName'];
            $data = ResAreaGroup::getSchoolTextBook($schoolId);
            if ($data['groupId'] == 0 || empty($data['groupId'])) {
                $groupId = 0;
                $existGroup = false;
            } else {
                $groupId = $data['groupId'];
                $existGroup = true;
            }
            $groupName = $existGroup == false ? '未找到区域组，请联系教学部设置区域组对应的教材版本！' : $data['groupName'];
            $this->view->setVars([
                'groupId' => $groupId,
                'groupName' => $groupName,
                'schoolId' => $schoolId,
                'existId' => $existGroup,
                'stage' => $this->schEnum['iStage'][$schoolData['iStage']],
                'stageId' => $schoolData['iStage']
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 贫困生列表
     *
     * @return View
     *
     * create by gby 20180806
     */
    public function poorStudentListAction()
    {
        Assets::easyUI('js/school/poorStudent.js');
        Assets::select2();
        Assets::sweetAlert2();
        $this->view->pick('school/poorStudentList');
        Main::showNavPosition();
        if (!Power::exist('School_poorStudentList')) {
            return $this->sendErrorResponse(403, '没有权限查看');
        }
        $listSearchArr = [];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_type', 'style' => 'width: 80px;', 'data' => [0 => '--等级--'] + $this->userEnum['iPoorLevel']];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： '];
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px'];
        return $this->view->setVars([
            'List' => Template::createList('list', 'School_poorStudent_List', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, false)
            ])
        ]);
    }

    /**
     * 获取贫困生数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by gby 20180806
     */
    public function getPoorStudentAction()
    {
        $key = $this->request->getPost('key', 'string');
        $iPoorLevel = $this->request->getPost('poorLevel', 'int');
        try {
            $schoolPower = User::getSchoolPower(true);
            if (count($schoolPower) < 1) {
                return $this->sendErrorResponse(403, '无查看权限');
            }
//            $parameters = [
//                'columns' => 'iUserId, sUserName, sLogonName, sAdClsName, iUserSex, iSchoolId, iPoorLevel, tCreateDate',
//                'conditions' => 'bDelete = 0 AND iPoorLevel != 0 AND iSchoolId in ({schoolId:array})',
//                'bind' => ['schoolId' => array_keys($schoolPower)]
//            ];
            $builder = $this->modelsManager->createBuilder()
                ->columns('user.iUserId, user.sUserName, user.sLogonName, user.sAdClsName, user.iUserSex, user.iSchoolId, user.iPoorLevel, user.tCreateDate')
                ->from(['user' => '\\Admin\\Models\\user\\XhsysUser'])
                ->where("user.bDelete = 0 AND user.iPoorLevel != 0 AND user.iSchoolId IN (" . implode(',', array_keys($schoolPower)) . ")");
            // 关键字查询
            if ($key) {
                // 通过学校名称查询
                $schools = School::searchSchool($key);
                $schoolId = array_intersect(array_keys($schoolPower), $schools);
                if (count($schoolId) >= 1) {
                    $builder->andWhere("user.iSchoolId IN (" . implode(',', $schoolId) . ")  OR user.sUserName like '%" . $key . "%' OR user.sLogonName like '%" . $key . "%'");
//                    $parameters['conditions'] .= " AND (iSchoolId in ({schoolId:array}) OR sUserName like :key: OR sLogonName like :logonName:)";
//                    $parameters['bind'] += ['schoolId' => implode(',', $schoolId), 'key' => '%'.$key.'%', 'logonName' => '%'.$key.'%'];
                } else {
                    // 通过学生名称查询
                    $builder->andWhere("user.sUserName like '%" . $key . "%' OR user.sLogonName like '%" . $key . "%'");
//                    $parameters['conditions'] .= " AND (sUserName like :key: OR sLogonName like :logonName:)";
//                    $parameters['bind'] += ['key' => '%'.$key.'%' , 'logonName' => '%'.$key.'%'];
                }
            };
            // 贫困生等级查询
            if ($iPoorLevel && $iPoorLevel != 0) {
                $builder->andWhere('user.iPoorLevel = :iPoorLevel:', ['iPoorLevel' => $iPoorLevel]);
//                $parameters['conditions'] .= " And iPoorLevel = :iPoorLevel:";
//                $parameters['bind'] += ['iPoorLevel' => $iPoorLevel];
            }
//            $data = Main::runModelPage('\\Admin\\Models\\user\\XhsysUser', $parameters, $this->userEnum);
            $data = Main::runBuilderPage($builder, $this->userEnum);
            Main::runSchoolNameByIdStr($data['rows'], ['iSchoolId' => 'iSchoolId']);

            foreach ($data['rows'] as &$row) {
                $apply = XhschoolApply::findFirst([
                    'conditions' => 'bDelete = 0 and iStudId = :userId: and iType = 2',
                    'bind' => ['userId' => $row['iUserId']]
                ]);
                if (!$apply) {
                    $row['iState'] = '未申请';
                } else {
                    if ($apply->iStatus == 1 or $apply->iStatus == 2 or $apply->iStatus == 3) {
                        $row['iState'] = '待审核';
                    }
                    if ($apply->iStatus == 4) {
                        $row['iState'] = "<i class='glyphicon glyphicon-ok'></i>";
                    }
                    if ($apply->iStatus == 5 or $apply->iStatus == 6 or $apply->iStatus == 7) {
                        $row['iState'] = "<i class='glyphicon glyphicon-remove'></i>";
                    }
                }
            }

            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 教师子女列表
     *
     * @return View
     *
     * create by gby 20180806
     */
    public function tchChildAction()
    {
        Assets::easyUI('js/school/schoolTchChild.js');
        Assets::select2();
        Assets::sweetAlert2();
        $this->view->pick('school/tchChild');
        Main::showNavPosition();
        if (!Power::exist('School_tchChild')) {
            return $this->sendErrorResponse(403, '无查看权限');
        }
        $listSearchArr = [];
        $listSearchArr[] = ['type' => 'select', 'id' => 'list_type', 'style' => 'width: 80px;', 'data' => [1 => '--类型--', 2 => '收费', 3 => '免费']];
        $listSearchArr[] = ['type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： '];
        $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px'];
        return $this->view->setVars([
            'List' => Template::createList('list', 'School_tchChild_list', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, false)
            ])
        ]);
    }

    /**
     * 获取教师子女数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by gby 20180806
     */
    public function getTchChildAction()
    {
        $iTchChild = $this->request->getPost('tchChild', 'int');
        $key = $this->request->getPost('key', 'string');
        try {
            $schoolPower = User::getSchoolPower(true);
            if (count($schoolPower) < 1) {
                return $this->sendErrorResponse(403, '无查看权限');
            }
            $builder = $this->modelsManager->createBuilder()
                ->columns(['user.iSchoolId', 'user.sLogonName', 'user.sAdClsName', 'userStud.iUserId', 'userStud.iTchChild', 'userStud.iDevCost', 'userStud.iSerCost'])
                ->from(['user' => '\\Admin\\Models\\user\\XhsysUser'])
                ->leftJoin('\\Admin\\Models\\user\\XhsysUserstud', 'userStud.iUserId = user.iUserId', 'userStud')
                ->where("userStud.bDelete = 0 AND userStud.iTchChild != 1 AND user.iSchoolId IN (" . implode(',', array_keys($schoolPower)) . ")")
                ->groupBy('user.iUserId');
            // 关键字查询
            if ($key) {
                // 通过学校名称查询
                $schools = School::searchSchool($key);
                $schoolId = array_intersect(array_keys($schoolPower), $schools);
                if (count($schoolId) >= 1) {
                    // 查询当前学校的所有用户
                    $builder->andWhere("user.iSchoolId IN (" . implode(',', $schoolId) . ")  OR user.sUserName like '%" . $key . "%' OR user.sLogonName like '%" . $key . "%' OR user.sAdClsName like '%" . $key . "%'");
                } else {
                    // 通过学生名称或登录名查询
                    $builder->andWhere("user.sUserName like '%" . $key . "%' OR user.sLogonName like '%" . $key . "%' OR user.sAdClsName like '%" . $key . "%'");
                }
            };
            // 教师子女类型查询
            if ($iTchChild && $iTchChild != 1) {
                $builder->andWhere('userStud.iTchChild = :tchChild:', ['tchChild' => $iTchChild]);
            }
            $data = Main::runBuilderPage($builder, $this->userEnum);
            Main::runUserNameById($data['rows'], ['iUserId' => 'sUserName'], true);
            Main::runSchoolNameByIdStr($data['rows'], ['iSchoolId' => 'sSchoolName'], true);

            foreach ($data['rows'] as &$row) {
                $apply = XhschoolApply::findFirst([
                    'conditions' => 'bDelete = 0 and iStudId = :userId: and iType = 1',
                    'bind' => ['userId' => $row['iUserId']]
                ]);
                if (!$apply) {
                    $row['iState'] = '未申请';
                } else {
                    if ($apply->iStatus == 1 or $apply->iStatus == 2 or $apply->iStatus == 3) {
                        $row['iState'] = '待审核';
                    }
                    if ($apply->iStatus == 4) {
                        $row['iState'] = "<i class='glyphicon glyphicon-ok'></i>";
                    }
                    if ($apply->iStatus == 5 or $apply->iStatus == 6 or $apply->iStatus == 7) {
                        $row['iState'] = "<i class='glyphicon glyphicon-remove'></i>";
                    }
                }
            }

            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 上传/查看缴费凭证
     *
     *
     * @return View|string
     *
     * create by zqk 20181129
     */
    public function uploadPayVoucherAction()
    {
        if (!Power::exist('School_List_Stud_UploadPayVou')) {
            return $this->sendViewError('无上传缴费凭证权限');
        }
        $iId = $this->request->getQuery('iId');
        $nowYear = date('Y');
        $chargeYear = [];
        for ($i = 0; $i < 5; $i++) {
            $chargeYear[$nowYear - $i] = $nowYear - $i;
        }
        $schoolId = $this->request->getQuery('schoolId');
        if (empty($schoolId)) {
            return $this->sendViewError('学校参数错误');
        }
        $schoolInfo = XhschoolInfo::findFirst($schoolId);
        if (!$schoolInfo) {
            return $this->sendViewError('学校信息错误');
        }
        $data = [];
        foreach ($chargeYear as $key => $val) {
            $users = $this->modelsManager->createBuilder()
                ->columns(['user.iUserId', 'user.sUserName', 'user.sLogonName', 'user.sAdClsName', 'user.iUserSex', 'user.bEbook', 'user.iDevSource', 'user.iPoorLevel', 'user.tCreateDate', 'user.sIdentityCode', 'pay.sPayVoucherUrl', 'pay.iState', 'pay.iId', 'pay.sRemarks', 'pay.iChargeYear'])
                ->addFrom('Admin\Models\user\XhsysUser', 'user')
                ->leftJoin('Admin\Models\user\XhsysUserPayVoucher', "pay.iUserId = user.iUserId AND pay.bDelete = 0  AND pay.iChargeYear = $val", 'pay')
                ->where('user.bDelete = 0 AND user.bDisable = 0')
                ->inWhere('user.iUserId', $iId)
                ->groupBy('user.iUserId')
                ->getQuery()
                ->execute()
                ->toArray();
            foreach ($users as $k => $user) {
                if (!$user['iId']) {
                    $users[$k]['iId'] = 0;
                    $users[$k]['iChargeYear'] = $val;
                }

                if ($user['iState'] == 1) {
                    $stateName = "<span style='color: #00c898'>" . self::$payVoucherState[$user['iState']] . "</span>";
                } elseif ($user['iState'] == 2) {
                    $stateName = "<span style='color: #008CBA'>" . self::$payVoucherState[$user['iState']] . "</span>";
                } elseif ($user['iState'] == 3) {
                    $stateName = "<span style='color: #ee0146'>" . self::$payVoucherState[$user['iState']] . "</span>";
                } else {
                    $stateName = "<span style='color: #ffa000'>未上传</span>";
                }
                $users[$k]['iStateName'] = $stateName;
                if (!$user['sPayVoucherUrl']) {
                    $users[$k]['fileInfo'] = '0';
                } else {
                    $fileInfoArr = json_decode($user['sPayVoucherUrl'], true);
                    $images = [];
                    foreach ($fileInfoArr as $value) {
                        if ($value) {
                            $num = strrpos($value, '.');
                            if (in_array(substr($value, $num + 1), ['jpg', 'jpeg', 'png', 'bpm', 'gif'])) {
                                $images[] = $value;
                            }
                        }
                    }
                    $users[$k]['fileInfo']['sImages'] = implode(',', $images);
                    $users[$k]['fileInfo']['ids'] = $users[$k]['iUserId'] . $users[$k]['iChargeYear'];
                }
            }
            $data = array_merge($data, $users);
        }
        if (empty($data)) {
            return $this->sendViewError('请选择要操作的学生');
        }
        Assets::viewer();
        Assets::easyUI('../customer/js/myMain.js');
        Assets::easyUI('js/school/uploadPayVoucher.js');
        Assets::importMainJs('assets/jquery/jquery.form.js');
        $this->di->get('assets')
            ->addCss('assets/fileinput/fileinput.css')
            ->addJs('customer/js/fileinput.min.js')//修改过的
            ->addJs('customer/js/zh.js');
        $formButtonArr[] = ['id' => 'bt_form_add', 'text' => '提交'];
        $formButtonArr[] = ['id' => 'bt_form_close', 'text' => '取消'];
        $this->view->setVars([
            'FormButton' => Template::createButtonToolBar($formButtonArr),
            'users' => $data,
            'chargeYear' => $chargeYear,
            'schoolId' => $schoolId,
            'payVoucherState' => self::$payVoucherState,
            'schoolName' => $schoolInfo->sSchoolName,
        ]);
        return $this->view->pick('school/uploadPayVoucher');
    }

    /**
     * 上传图片
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20181119
     */
    public function uploadFileAction()
    {
        if (!$this->request->hasFiles()) {
            return $this->sendErrorResponse(400, '缺少文件');
        }
        $file = $this->request->getUploadedFiles()[0];
        $type = $file->getType();
        $types = [
            'image/jpeg',
            'image/png',
            'image/gif',
            'image/bpm',
        ];
        if (!in_array($type, $types)) {
            return $this->sendErrorResponse(500, '文件非图片格式');
        };
        $filePath = Tool::buildPath(Main::getConfigByName('fileSave')['temp'], $file->getName());
        $fileName = $file->getName();
        $file->moveTo($filePath);
        $url = Main::uploadToFileManageSystem($filePath, 'img', null, true);
        if (!$url) {
            return $this->sendErrorResponse(500, '文件上传失败:没有文件url');
        } else {
            return $this->sendSuccessResponse(['url' => $url, 'fileName' => $fileName]);
        }
    }

    /**
     * 保存缴费凭证
     *
     * @return array|bool|mixed|null|\Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by zqk 20181119
     */
    public function savePayVoucherAction()
    {
        if (!Power::exist('School_List_Stud_UploadPayVou')) {
            return $this->sendErrorResponse(403, '无上传缴费凭证权限');
        }
        $data = $this->request->getPost();
        $selectYear = $data['selectYear'];
        if (empty($data['iSchoolId'])) {
            return $this->sendErrorResponse(400, '学校参数错误');
        }
        if (empty($data['payVoucher'])) {
            return $this->sendErrorResponse(400, '缴费凭证为空');
        }
        try {
            foreach ($data['iUserId'][$selectYear] as $v) {
                if (empty($data['payVoucher'][$v][$selectYear])) {
                    continue;
                }
                $payObj = XhsysUserPayVoucher::findFirst([
                    'conditions' => 'bDelete = 0 AND iUserId = ' . $v . " and iChargeYear = $selectYear",
                ]);
                if (empty($payObj)) {
                    $payObj = new XhsysUserPayVoucher();
                } else {
                    if ($payObj->iState != 3) {
                        continue;
                    }
                }
                $payObj->iState = 1;
                $payObj->iUserId = $v;
                $payObj->iChargeYear = $selectYear;
                $payObj->iSchoolId = $data['iSchoolId'];
                $payObj->sPayVoucherUrl = json_encode($data['payVoucher'][$v][$selectYear]);
                $payObj->sAdClsName = $data['sAdClsName'][$v][$selectYear];
                $payObj->save();
            }
            return $this->sendSuccessResponse('上传成功!');
        } catch (Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 附件审核查看页面
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by zqk 20180920
     */
    public function showPayVoucherAction()
    {
        $userIds = $this->request->getQuery('userIds');
        $nowYear = date('Y');
        $year = $this->request->getQuery('year', 'int', $nowYear);
        $userIds = explode(',', $userIds);
        $users = $this->modelsManager->createBuilder()
            ->columns(['user.iUserId', 'user.sUserName', 'user.sLogonName', 'user.sAdClsName', 'user.iUserSex', 'user.bEbook', 'user.iDevSource', 'user.iPoorLevel', 'user.tCreateDate', 'user.sIdentityCode', 'pay.sPayVoucherUrl', 'pay.iState', 'pay.iId', 'pay.sRemarks', 'pay.iChargeYear'])
            ->addFrom('Admin\Models\user\XhsysUser', 'user')
            ->leftJoin('Admin\Models\user\XhsysUserPayVoucher', "pay.iUserId = user.iUserId AND pay.iChargeYear = $year And pay.bDelete = 0", 'pay')
            ->where('user.bDelete = 0 AND user.bDisable = 0')
            ->inWhere('user.iUserId', $userIds)
            ->groupBy('user.iUserId')
            ->getQuery()
            ->execute()
            ->toArray();
        if (empty($users)) {
            return $this->sendViewError('请选择要操作的学生');
        }
        foreach ($users as $k => $user) {
            if (!$user['iId']) {
                $users[$k]['iId'] = 0;
                $users[$k]['iChargeYear'] = $nowYear;
            } else {
                $logs = XhsysUserPayVoucherLog::find([
                    'columns' => 'iId,sContent,tCreateDate',
                    'conditions' => 'bDelete = 0 And iPayId = ' . $user['iId'],
                    'order' => 'iId desc',
                ])->toArray();
                foreach ($logs as $ke => $log) {
                    $logs[$ke]['sContent'] = json_decode($logs[$ke]['sContent'], true);
                }
                $users[$k]['log'] = $logs;
                $users[$k]['logNum'] = count($logs);
            }
            if ($user['iState'] == 1) {
                $stateName = "<span style='color: #00c898'>" . self::$payVoucherState[$user['iState']] . "</span>";
            } elseif ($user['iState'] == 2) {
                $stateName = "<span style='color: #008CBA'>" . self::$payVoucherState[$user['iState']] . "</span>";
            } elseif ($user['iState'] == 3) {
                $stateName = "<span style='color: #ee0146'>" . self::$payVoucherState[$user['iState']] . "</span>";
            } else {
                $stateName = "<span style='color: #565656'>未上传</span>";
            }

            $users[$k]['iStateName'] = $stateName;

            if (!$user['sPayVoucherUrl']) {
                $users[$k]['fileInfo'] = 0;
            } else {
                $fileInfoArr = json_decode($user['sPayVoucherUrl'], true);
                $images = $files = [];
                foreach ($fileInfoArr as $value) {
                    if ($value) {
                        $num = strrpos($value, '.');
                        if (in_array(substr($value, $num + 1), ['jpg', 'jpeg', 'png', 'bpm', 'gif'])) {
                            $images[] = $value;
                        } else {
                            $files[] = $value;
                        }
                    }
                }
                $users[$k]['fileInfo']['sImages'] = implode(',', $images);
                $users[$k]['fileInfo']['ids'] = $users[$k]['iUserId'] . $users[$k]['iChargeYear'];
                $users[$k]['fileInfo']['sFiles'] = implode(',', $files);
            }
        }
        $this->view->pick('school/showFileForm');
        Assets::viewer();
        Assets::easyUI('../customer/js/myMain.js');
        Assets::importJs('js/school/showFileForm.js');
        return $this->view->setVars([
            'users' => $users,
            'checkPower' => Power::exist('School_List_Stud_CheckPayVou')
        ]);
    }

    public function delFileAction()
    {
        $iUserId = $this->request->getPost('iUserId', 'int');
        $num = $this->request->getPost('num', 'int');
        if (empty($iUserId) || !isset($num)) {
            return $this->sendErrorResponse('500', '参数错误!');
        }
        $payInfo = XhsysUserPayVoucher::findFirst([
//            'columns' => 'sPayVoucherUrl',
            'conditions' => 'bDelete=0 AND iUserId = :iUserId:',
            'bind' => array('iUserId' => $iUserId),
        ]);
        if (empty($payInfo)) {
            return $this->sendErrorResponse('500', '没有相关凭证附件!');
        }
        $fileInfoArr = json_decode($payInfo->sPayVoucherUrl, true);
        array_splice($fileInfoArr, $num, 1);
        $payVoucherUrl = json_encode($fileInfoArr);
        $payInfo->sPayVoucherUrl = $payVoucherUrl;
        $re = $payInfo->save();
        if ($re) {
            return $this->sendSuccessResponse('删除成功!');
        } else {
            return $this->sendErrorResponse('500', '删除失败!');
        }
    }

    public function deleteFileAction()
    {
        return $this->sendSuccessResponse('删除成功!');
    }

    /**
     * 审核凭证
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by zqk 20181126
     */
    public function checkPayVouCherAction()
    {
        $iId = $this->request->getPost('iId', 'int');
        $result = $this->request->getPost('iResult', 'int');
        if (!$iId) {
            return $this->sendErrorResponse('400', '参数错误！');
        }
        $sRemark = $this->request->getPost('sRemarks', 'string');
        $this->db->begin();
        $payObj = XhsysUserPayVoucher::findFirst([
            'conditions' => "iId = $iId AND bDelete = 0 ",
        ]);
        if (!$payObj) {
            return $this->sendErrorResponse('500', '凭证信息不存在！');
        }
//        if ($payObj->iState != 1) {
//            return $this->sendErrorResponse('500', '凭证信息非待审核');
//        }
        if (!in_array($result, [2, 3])) {
            return $this->sendErrorResponse('500', '审核状态错误');
        }
        $payObj->iState = $result;
        $payObj->sRemarks = $sRemark;
        $re = $payObj->save();
        if (!$re) {
            $this->db->rollback();
            return $this->sendErrorResponse('500', '审核失败');
        }
        //审核日志
        $content['userName'] = Main::getLoginUserInfo('userName');
        $content['content'] = $sRemark;
        $content['action'] = $result == 2 ? '审核通过' : '审核未通过';
        $content['title'] = '审核缴费凭证';
        $logObj = new XhsysUserPayVoucherLog();
        $logObj->iPayId = $payObj->iId;
        $logObj->sContent = json_encode($content);
        $res = $logObj->save();
        if (!$res) {
            $this->db->rollback();
            return $this->sendErrorResponse('500', '审核失败');
        }
        $this->db->commit();
        return $this->sendSuccessResponse('审核成功');
    }

    /**
     * 获取统计数据接口
     *
     * @return \Phalcon\Http\ResponseInterface
     *
     * create by sqb 20190118
     */
    public function getStatDataAction()
    {
        $schoolId = $this->request->getPost('schoolId');
        $users = XhsysUser::find([
            'columns' => 'iUserId,sAdClsName,iUserSex,sBirthday,iUserType',
            'conditions' => 'bDelete = 0 and iSchoolId = :schoolId:',
            'bind' => ['schoolId' => $schoolId],
        ]);

        $data = ['stu_grade' => [], 'tch_sex' => [], 'tch_age' => [], 'stu_sex' => [], 'right' => []];
        if (!$users) {
            return $this->response->setJsonContent($data);
        }

        $users = $users->toArray();
        $grade = $stuSex = $tchSex = $tchAge = [];
        foreach ($users as $user) {
            if ($user['iUserType'] == 1 && is_numeric($user['sAdClsName']) && strlen($user['sAdClsName']) == 4) {
                $grade[substr($user['sAdClsName'], 0, 2) . '级']++;
            }

            if ($user['iUserType'] == 1) {
                if ($user['iUserSex'] == 0) {
                    $stuSex['未知']++;
                }
                if ($user['iUserSex'] == 1) {
                    $stuSex['男']++;
                }
                if ($user['iUserSex'] == 2) {
                    $stuSex['女']++;
                }
            }

            if ($user['iUserType'] == 4) {
                if ($user['iUserSex'] == 0) {
                    $tchSex['未知']++;
                }
                if ($user['iUserSex'] == 1) {
                    $tchSex['男']++;
                }
                if ($user['iUserSex'] == 2) {
                    $tchSex['女']++;
                }

                $age = date('Y') - date('Y', strtotime($user['sBirthday']));
                if ($age >= 20 and $age <= 30) {
                    $tchAge['20-30']++;
                } elseif ($age > 30 and $age <= 40) {
                    $tchAge['30-40']++;
                } elseif ($age > 40 and $age <= 50) {
                    $tchAge['40-50']++;
                } else {
                    $tchAge['其它']++;
                }
            }
        }

        //教师交流分享
        $share = XhschoolShare::count([
            'conditions' => 'bDelete = 0 AND iSchoolId = :iSchoolId:',
            'bind' => ['iSchoolId' => $schoolId],
        ]);

        //学校活动
        $activity = XhresArticle::count([
            'conditions' => 'bDelete = 0 and iArtType = 9 and iSchoolId = :schoolId:',
            'bind' => ['schoolId' => $schoolId]
        ]);

        //运营案例
        $yunying = XhresArticle::count([
            'conditions' => 'bDelete = 0 and iArtType = 7 and iSchoolId = :schoolId:',
            'bind' => ['schoolId' => $schoolId]
        ]);

        //外校参观
        $visits = XHSchoolVisit::count([
            'conditions' => 'iSchoolId = :iSchoolId:',
            'bind' => ['iSchoolId' => $schoolId],
        ]);

        //运营状况
        $examine = new SchoolExamineController();
        $examine = $examine->getChart([$schoolId]);

        $data = ['stu_grade' => $grade, 'stu_sex' => $stuSex, 'tch_sex' => $tchSex, 'tch_age' => $tchAge, 'right' => ['交流分享' => $share, '学校活动' => $activity, '运营案例' => $yunying, '外校参观' => $visits]];
        $arr = [];
        foreach ($data as $pie => $datum) {
            if ($pie == 'right') {
                continue;
            }
            foreach ($datum as $k => $v) {
                $arr[$pie][] = [
                    'name' => $k,
                    'value' => $v
                ];
            }
        }
        $arr['right'] = [
            'name' => array_keys($data['right']),
            'value' => array_values($data['right'])
        ];
        $arr['examine'] = current($examine);

        //学校总分
        $examineInfo = XhstatsExamine::getExamineInfo($schoolId, date('Y-m'));
        $arr['score'] = [
            'score' => $examineInfo['iScore'],
            'format' => $examineInfo['iScore'] == 0 ? 0 : round(($examineInfo['iScore'] / 120) * 100, 2),
            'end_time' => $examineInfo['tCreateDate']
        ];

        return $this->response->setJsonContent($arr);
    }

    /**
     * 项目历史
     */
    public function projectAction()
    {
        $this->view->pick('school/project');
        Assets::easyUI('js/school/project.js');

        if (Power::exist('School_ProjectHistory_Add')) {
            $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_add', 'text' => '增加', 'icon' => 'fa-plus'];
        }
        if (Power::exist('School_ProjectHistory_Del')) {
            $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash'];
        }
        if (Power::exist('School_ProjectHistory_Check')) {
            $listButtonArr[] = ['id' => 'bt_list_check', 'text' => '审核', 'plan' => 'true', 'icon' => 'fa-check', 'style' => 'margin-left:10px;cursor: pointer;'];
        }
        $this->view->setVars(array(
            'List' => Template::createList('list', 'School_Project', [
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
        ));
    }

    /**
     * 项目历史表单
     *
     * @return View
     *
     * create by sqb 20190117
     */
    public function projectFormAction()
    {
        Assets::easyUI();
        Assets::datetimePicker();
        Assets::importJs('js/school/projectForm.js');

        $this->view->pick('school/projectForm');
        $cooperate = XhsysEnum::getEnumByNodeName('收费模式');
        $project = 1;
        $planId = 0;
        $id = $this->request->get('id');
        if ($id) {
            $project = XhProjectHistory::findFirst($id)->toArray();
            $planId = $project['iPlanId'];
            if ($planId) {
                $project['sCooperate'] = explode(',', $project['sCooperate']);
                $arr = [];
                foreach ($project['sCooperate'] as $item) {
                    $arr[] = $cooperate[$item];
                }
                $project['sCooperate'] = implode(',', $arr);
            }
        }
        $this->view->setVar('project', json_encode($project));

        return $this->view->setVars([
//            'Form' => Template::createForm('Project_Form'),
            'project' => json_encode($project),
            'cooperate' => $cooperate,
            'planId' => $planId
        ]);
    }

    /**
     * 项目历史保存
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by sqb 20190117
     */
    public function projectSaveAction()
    {
        if (!Power::exist('School_ProjectHistory_Edit') || !Power::exist('School_ProjectHistory_Add')) {
            return $this->sendViewError('无权限');
        }

        $data = $this->request->getPost();

        try {
            $this->db->begin();
            $project = new XhProjectHistory();
            if ($data['iId']) {
                if (!XhProjectHistory::isLocalData([$data['iId']])) {
                    return $this->sendErrorResponse(500, '编辑失败，包含无法操作的记录');
                }
                if (XhProjectHistory::findFirst($data['iId'])->iState != 0) {
                    return $this->sendErrorResponse(500, '已审核过的不能更改');
                }
                $project = XhProjectHistory::findFirst($data['iId']);
            }

            $project->sCooperate = $data['sCooperate'];
            $project->sClass = $data['sClass'];
            $project->iTeacher = $data['iTeacher'];
            $project->iStudent = $data['iStudent'];
            $project->tTime = $data['tTime'];
            $project->iSchoolId = $data['iSchoolId'];

            if ($project->save()) {
                $this->db->commit();
                return $this->sendSuccessResponse('保存成功');
            }
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 获取项目历史数据
     *
     * @return \Phalcon\Http\ResponseInterface
     *
     * create by sqb 20190118
     */
    public function getProjectDataAction()
    {
        if (!Power::exist('School_ProjectHistory')) {
            return $this->sendViewError('无权限');
        }

        $schoolId = $this->request->get('schoolId');

        $enum = [
            'iState' => [
                '0' => '',
                '1' => "<i class='glyphicon glyphicon-ok'></i>",
                '2' => "<i class='glyphicon glyphicon-pause'></i>",
            ],
        ];
        $cooperate = XhsysEnum::getEnumByNodeName('收费模式');

        if ($schoolId) {
            $parameters = [
                'conditions' => 'iSchoolId = :schoolId: and bDelete = 0',
                'bind' => ['schoolId' => $schoolId],
                'order' => 'tTime asc'
            ];
            $data = Main::runModelPage('\\Admin\\Models\\school\\XhProjectHistory', $parameters, $enum);
            foreach ($data['rows'] as &$datum) {
                $coopArr = explode(',', $datum['sCooperate']);
                $arr = [];
                foreach ($coopArr as $item) {
                    $arr[] = $cooperate[$item];
                }
                $datum['sCooperate'] = implode(',', $arr);
                if ($datum['iPlanId']) {
                    $datum['tTime'] = "<span style='background-color: #c0c0c0;display:inline-table;width: 100%;height: 100%;'>{$datum['tTime']}</span>";
                }
            }

            return $this->response->setJsonContent($data);
        }

        return $this->response->setJsonContent([]);
    }

    /**
     * 删除项目历史
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by sqb 20190118
     */
    public function delProjectAction()
    {
        if (!Power::exist('School_ProjectHistory_Del')) {
            return $this->sendViewError('无权限');
        }

        $ids = $this->request->getPost('ids');

        if (!XhProjectHistory::isLocalData($ids)) {
            return $this->sendErrorResponse(500, '删除失败，包含无法操作的记录');
        }

        $res = XhProjectHistory::deleteRecord('iId', $ids);

        if ($res) {
            return $this->sendSuccessResponse('删除成功');
        }
        return $this->sendErrorResponse(500, '删除失败');
    }

    /**
     * 项目历史审核
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by sqb 20190118
     */
    public function checkProjectAction()
    {
        if (!Power::exist('School_ProjectHistory_Check')) {
            return $this->sendViewError('无权限');
        }

        $ids = $this->request->getPost('ids');

        if (!XhProjectHistory::isLocalData($ids)) {
            return $this->sendErrorResponse(500, '审核失败，包含无法操作的记录');
        }

        $res = XhProjectHistory::checkProject($ids, 1);
        if ($res) {
            return $this->sendSuccessResponse('操作成功');
        }

        return $this->sendErrorResponse(500, '操作失败');
    }

    /**
     * 学校详情页
     *
     * @return View
     *
     * create by sqb 20190123
     */
    public function schoolInfoAction()
    {
        $schoolId = $this->request->get('iSchoolId');
        $schoolName = $this->request->get('sSchoolName');

        $this->view->pick('school/schoolInfo');
        Main::showNavPosition();
        Assets::select2();
        Assets::easyUI('js/school/schoolInfo.js');
        Assets::xhChart();

        $power['runCase'] = Power::exist('School_RunCase');
        $power['activity'] = Power::exist('School_Activity');
        $power['schoolShare'] = Power::exist('School_Share');
        $power['tchBook'] = true;
        $power['bookVer'] = Power::exist('School_BookVer');
        $power['schoolVisit'] = Power::exist('School_Visit');
        $power['schoolStat'] = Power::exist('School_Stat');
        $power['schoolProject'] = Power::exist('School_ProjectHistory');
        $power['schoolEdit'] = Power::exist('School_List_Edit');
        $powerTags = [
            'School_List_Stud',//学生管理
            'School_List_Tch',//教师管理
            'School_List_Group',//应用组管理
            'School_List_Manage',//学校管理
            'School_List_App',//应用管理
            'School_List_QBank',//题库管理
            'School_List_OtherUser',//其他用户
            'School_List_BrushGroup',//刷题王分组
            'School_List_Books',//校本库
        ];
        foreach ($powerTags as $powerTag) {
            $power[$powerTag] = Power::exist($powerTag);
        }

        $field = ['iStatus', 'iSchoolId', 'sSchoolName', 'sCode', 'iStage', 'iRunLevel', 'iType', 'iApprovalStatus', 'bWelfare', 'iExamineMode', 'brushGroupStatus', 'iSchoolIdModify'];
        if ($power['schoolStat']) {
            $field[] = 'class';
            $field[] = 'teacher';
            $field[] = 'student';
        }

        $this->runEnum();

        return $this->view->setVars([
            'Form' => Template::createForm('XHSchool_Info', $this->schEnum),
            'power' => $power,
            'schoolId' => $schoolId,
            'schoolName' => $schoolName,
        ]);
    }

    /**
     * 更改账号用途
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by sqb 20190123
     */
    public function useTypeAction()
    {
        $ids = $this->request->getPost('ids');
        $type = $this->request->getPost('type');
        if (!$ids || !$type) {
            return $this->sendErrorResponse(400, '缺少参数');
        }

        try {
            $result = $this->modelsManager->executeQuery(
                'update \\Admin\\Models\\user\\XhsysUser set iType = :iType: where iUserId in ({ids:array})',
                ['iType' => $type, 'ids' => $ids]
            );
            if (!$result) {
                throw new \Exception('保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 转学页面
     *
     * @return mixed
     *
     * create by sqb 20190125
     */
    public function changeSchoolAction()
    {
        Assets::easyUI();
        Assets::select2();
        Assets::importJs('js/school/changeSchool.js');
        $this->view->pick('school/changeSchool');

        $ids = $this->request->get('ids');

        $school = XhschoolInfo::find([
            'columns' => 'iSchoolId,sSchoolName',
            'conditions' => 'bDelete = 0',
        ])->toArray();
        $data = [];
        foreach ($school as $item) {
            $data[$item['iSchoolId']] = $item['sSchoolName'];
        }

        return $this->view->setVars([
            'school' => $data,
            'ids' => $ids
        ]);
    }

    /**
     * 申请转校
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Exception
     *
     * create by sqb 20190125
     * modify by sqb 20190222 转校逻辑重构
     */
    public function doChangeSchoolAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        $ids = $this->request->getPost('ids');
        $class = $this->request->getPost('class');
        $ids = explode('_', $ids);

        School::changeSchool($ids, $schoolId, $class);

        return $this->sendSuccessResponse('转校成功');
    }

    /**
     * 转校页
     *
     * create by sqb 20190128
     */
    public function changeSchoolListAction()
    {
        if (!Power::exist('ChangeSchool_List')) {
            return $this->sendViewError('无查看权限');
        }

        $this->view->pick('school/changeSchoolList');
        Assets::easyUI('js/school/changeSchoolList.js');
        $listButtonArr = [];
        $listSearchArr[] = [
            'type' => 'select',
            'id' => 'list_search_status',
            'data' => [0 => '未审核', 1 => '已审核']
        ];
        $listSearchArr[] = [
            'type' => 'select',
            'id' => 'list_search_change_status',
            'data' => [-1 => '--转校状态--', 0 => '转校中', 1 => '已转校']
        ];
//        $listSearchArr[] = ['type' => 'text', 'id' => 'list_search_vague', 'label' => ' 搜索： '];
        if (Power::exist('ChangeSchool_Check')) {
            $listButtonArr[] = ['id' => 'bt_list_check', 'text' => '审核', 'plain' => 'true', 'icon' => 'fa-pencil'];
        }
        if (Power::exist('ChangeSchool_Check_Final')) {
            $listButtonArr[] = ['id' => 'bt_list_check_final', 'text' => '转校', 'plain' => 'true', 'icon' => 'fa-pencil'];
        }
        if (Power::exist('ChangeSchool_Del')) {
            $listButtonArr[] = ['plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash'];
        }

        $this->view->setVars(array(
            'List' => Template::createList('list', 'School_Change',[
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
        ));
    }

    /**
     * 转校审核
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by sqb 20190130
     */
    public function changeSchoolCheckAction()
    {
        if (!Power::exist('ChangeSchool_Check')) {
            return $this->sendViewError('无审核权限');
        }

        $ids = $this->request->getPost('ids');

        try {
            $this->db->begin();
            XhsysUserHistory::find([
                'conditions' => "iId in ({ids:array})",
                'bind' => ['ids' => $ids]
            ])->update(['iStatus' => 1]);

            $this->db->commit();
            return $this->sendSuccessResponse('审核成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 转校审核（最终）
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws \Exception
     *
     * create by sqb 20190221
     */
    public function changeSchoolCheckFinalAction()
    {
        if (!Power::exist('ChangeSchool_Check_Final')) {
            return $this->sendViewError('无转校权限');
        }

        $ids = $this->request->getPost('ids');

        $history = XhsysUserHistory::find([
            'conditions' => 'iId in (' . implode(',', $ids) . ') and bDelete = 0',
            'columns' => 'iUserId,iStatus',
        ])->toArray();

        foreach ($history as $item) {
            if ($item['iStatus'] == 0) {
                throw new \Exception('未审核的用户不允许转校！');
            }
        }

        try {
            $this->db->begin();

            XhsysUserHistory::find([
                'conditions' => "iId in ({ids:array}) and bDelete = 0",
                'bind' => ['ids' => $ids]
            ])->update(['iChangeStatus' => 1]);

            foreach ($ids as $id) {
                $userHistory = XhsysUserHistory::find([
                    'columns' => 'iUserId,sInInfo,iId',
                    'conditions' => "iId=:id:",
                    'bind' => ['id' => $id],
                    'order' => 'iId desc',
                    'limit' => 1
                ])->toArray();

                $info = json_decode($userHistory[0]['sInInfo'], true);

                XhsysUser::find([
                    'conditions' => "iUserId = :id:",
                    'bind' => ['id' => $userHistory[0]['iUserId']]
                ])->update(['iSchoolId' => $info['schoolId'], 'sAdClsName' => $info['class']]);
            }

            $this->db->commit();
            return $this->sendSuccessResponse('转校成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 获取转校记录
     *
     * @return mixed
     * @throws \Exception
     *
     * create by sqb 20190128
     */
    public function getChangeSchoolDataAction()
    {
        if (!Power::exist('ChangeSchool_List')) {
            return $this->sendViewError('无查看权限');
        }
        $status = $this->request->getPost('status', 'int');
        $changeStatus = $this->request->getPost('changeStatus', 'int');

        $data = School::getChangeSchoolList($changeStatus, $status ?? 0);

        return $this->response->setJsonContent($data);
    }

    /**
     * 删除转校申请
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by sqb 20190221
     */
    public function delChangeSchoolAction()
    {
        if (!Power::exist('ChangeSchool_Del')) {
            return $this->sendViewError('无查看权限');
        }

        $ids = $this->request->getPost('ids');
        try {
            XhsysUserHistory::deleteRecord('iId', $ids);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
        return $this->sendSuccessResponse('操作成功');
    }

    /**
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws XhException
     *
     * create by sqb 20190130
     */
    public function addSignInDataAction()
    {
        if (!Power::exist('School_User_Sign')) {
            return $this->sendViewError('无操作权限');
        }

        $info = $this->request->getPost('info');
        $type = $this->request->getPost('type', 'int');
        $status = $this->request->getPost('status', 'int');

        $res = Device::addSignInData($info, $type, $status);

        if ($res) {
            return $this->sendSuccessResponse('操作成功');
        }
        return $this->sendErrorResponse(400, '操作失败');
    }

    /**
     * 用户配置列表
     *
     * @return mixed
     * @throws XhException
     *
     * create by sqb 20190212
     */
    public function userConfigureListAction()
    {
        if (!Power::exist('School_List_User_Configure_List')) {
            return $this->sendErrorResponse(400, '无查看权限');
        }
        $ids = $this->request->getQuery('ids', 'string');
        $this->view->pick('school/userConfigureList');
        $this->assets->addCss('assets/bootstrap/bootstrap-switch.min.css', true)
            ->addCss('assets/toast/jquery.toast.css', true, true);
        $this->assets->addJs('assets/bootstrap/bootstrap-switch.min.js', true)
            ->addJs('assets/toast/jquery.toast.js', true, true);
        Assets::importJs('js/school/userConfigureList.js');

        $configure = UserService::getUserConfigure();
        $userIdArr = explode(',', $ids);
        $userConfigure = [];
        if (count($userIdArr) == 1) {
            $userConfigure = UserService::getUserConfigureByUserId($ids);
        }
        return $this->view->setVars([
            'configure' => $configure,
            'ids' => $ids,
            'userConfigure' => $userConfigure
        ]);
    }

    /**
     * 用户配置设置接口
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * @throws XhException
     *
     * create by sqb 20190212
     */
    public function userConfigureSetAction()
    {
        if (!Power::exist('School_List_User_Configure_Set')) {
            return $this->sendErrorResponse(400, '无操作权限');
        }
        $userIds = $this->request->getPost('ids', 'string');
        $keys = $this->request->getPost('keys', 'string');

        UserService::setUserConfigure($userIds, $keys);

        return $this->sendSuccessResponse('操作成功');
    }
}
